任务是定义一个函数,该函数count_vowels(text)
接受一个字符串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})
那么,我的代码有什么问题,如何获得与示例中相同的结果?