简体   繁体   中英

Python, counting from an inputted string. Needs to be returned in a specific order?

So i am typing a code where a user will need to input >>Count('bla bla bla') and the program needs to count the in the bla bla bla phrase and return the word with its count in this SPECIFIC order.

Any Help?

Your count function is not used correctly. You want text.search(vowel) , not vowel.search(text)

>>> s = 'this is some string with a lot of vowels'
>>> vowels = 'aeiou'
>>> {i : s.count(i) for i in vowels}
{'a': 1, 'i': 4, 'e': 2, 'u': 0, 'o': 4}

Dictionaries have no order, so if you want the count in vowel order:

>>> [(i,s.count(i)) for i in vowels]
[('a', 1), ('e', 2), ('i', 4), ('o', 4), ('u', 0)]
def vowelCount(text):
    vowels = 'aeiou'
    return ("a, e, i, o, and u appear, respectively, %s times." %", ".join([ str(text.count(x)) for x in vowels]))

print vowelCount('bla bla bla')

Hope this helps.

You made a typo:

def vowelCount(text):
    vowels = 'aeiou'
    counts = {x:text.count(x) for x in vowels}
    keys = counts.keys()
    values = counts.values()
    return ','.join(keys[:-1]) + ' and '+ keys[-1] +' appear, respectively, '+ ','.join(str(v) for v in values)+' times.'

The code as written doesn't even examine the input text at all. You're counting the number of times each vowel appears in vowels .

Replace with text.count(i) instead of vowels.count(i) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM