1

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

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

4

5 回答 5

2
return '\n'.join( '%s: %s' % item for item in counts.items())
于 2010-12-07T21:47:47.070 回答
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
于 2010-12-07T21:48:21.607 回答
1

结果是一样的。您是指结果的格式吗?在函数末尾编写一些代码,将结果字典转换为正确格式的字符串。

于 2010-12-07T21:42:51.093 回答
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
于 2010-12-08T01:32:13.397 回答
0

我认为,在这里您将返回整数类型的整个字典。尝试遍历字典并打印每个键以根据需要对其进行格式化。

于 2010-12-07T21:44:20.563 回答