计算项目序列,python
任务是定义一个函数 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})
那么,我的代码有什么问题以及如何获得与示例中相同的结果?
The task is to define a function count_vowels(text)
that takes a string text
, counts the
vowels in text (using a Python dictionary for the counting), and returns the
vowel frequency information as a string.
Example:
>>> count_vowels('count vowels')
'e: 1\nu: 1\no: 2'
>>> print count_vowels('count vowels')
e: 1
u: 1
o: 2
so far I've come up with:
>>> 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})
so, what's wrong with my code and how do I get the same result as in the example?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您使用的是 Python 2.7,请尝试使用计数器:
这会导致输出:
如果您有较早版本的 Python,您仍然可以使用 defaultdict,只需使用相同的
iteritems()
循环:If you are using Python 2.7, try using a counter:
This results in the output:
If you have an earlier version of Python, you can still use your defaultdict, and just use the same
iteritems()
loop:结果是一样的。您指的是结果的格式吗?在函数末尾编写一些代码,将结果字典转换为正确格式的字符串。
The result is the same. Are you referring to how the result is formatted? Write some code at the end of the function that converts the resulting dictionary into a string in the right format.
我会尝试:
这输出:
I would try:
This outputs:
我认为,在这里您将返回整数类型的整个字典。尝试迭代字典并打印每个键以按照您想要的方式格式化它。
Here you're returning the entire dictionary of an integer type, I think. Try iterating through the dictionary and printing each key to format it like you want.