counting a sequence of item, python
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:开发者_JAVA技巧 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?
If you are using Python 2.7, try using a counter:
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
This results in the output:
e 1
u 1
o 2
If you have an earlier version of Python, you can still use your defaultdict, and just use the same iteritems()
loop:
for k, v in counts.iteritems():
print k, v
return '\n'.join( '%s: %s' % item for item in counts.items())
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:
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]
This outputs:
>>> count_vowels('count vowels')
'e: 1\nu: 1\no: 2'
>>> print count_vowels('count vowels')
e: 1
u: 1
o: 2
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.
精彩评论