计算一系列项目,python

时间:2010-12-07 21:36:23

标签: python dictionary nltk

任务是定义一个函数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})

所以,我的代码有什么问题,我如何获得与示例中相同的结果?

5 个答案:

答案 0 :(得分:2)

return '\n'.join( '%s: %s' % item for item in counts.items())

答案 1 :(得分:2)

如果您使用的是Python 2.7,请尝试使用计数器:

from collections import Counter
counts = Counter(c for c in 'count vowels' if c in 'aeoiu')
for k, v in counts.iteritems():
    print k, v

这导致输出:

e 1
u 1
o 2

如果你有早期版本的Python,你仍然可以使用你的defaultdict,并且只使用相同的iteritems()循环:

for k, v in counts.iteritems():
    print k, v

答案 2 :(得分:1)

结果是一样的。你指的是如何格式化结果?在函数末尾写一些代码,将生成的字典转换为正确格式的字符串。

答案 3 :(得分:1)

我会尝试:

def count_vowels(text):
vowels = 'aeiou'
counts ={}
s = ''
for letter in text:
    if letter in vowels:
        if letter in counts:
            counts[letter] += 1
        else:
            counts[letter] = 1
for item in counts:
    s = s + item + ': ' + str(counts[item]) + '\n'
return s[:-1]

输出:

>>> count_vowels('count vowels')
'e: 1\nu: 1\no: 2'
>>> print count_vowels('count vowels')
e: 1
u: 1
o: 2

答案 4 :(得分:0)

我想你在这里返回一个整数类型的整个字典。尝试遍历字典并打印每个键,以便按照您的需要对其进行格式化。