文字列text
を取り、テキスト中の 母音をカウントするためにPython辞書を使って関数count_vowels(text)
を定義し、 母音頻度情報を文字列として返します。アイテムのシーケンスを数える、python
>>> count_vowels('count vowels')
'e: 1\nu: 1\no: 2'
>>> print count_vowels('count vowels')
e: 1
u: 1
o: 2
これまで私が思いついたのは次のとおりです。
>>> def count_vowels(text):
counts = nltk.defaultdict(int)
for w in text:
if w in 'aeoiu':
counts[w] += 1
return counts
>>> count_vowels('count vowels')
defaultdict(<type 'int'>, {'e': 1, 'u': 1, 'o': 2})
だから、私のコードで何が問題なのですか?
Pythonは組み込みの 'collections.defaultdict'を持っています。 'nltk.defaultdict'を使うのは少しばかり混乱します。 –
宿題に[宿題]タグを付けてください。 –
短い答え: 'count_vowels()'関数は文字列ではなく 'nltk.defaultdict(int)'インスタンスを返しています。関数の最後に 'defaultdict'で終わるものに基づいてコードを返すコードを追加し、あなたの望むようにフォーマットする必要があります。 – martineau