[英]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. 因此,我正在输入用户需要输入>> Count('bla bla bla')的代码,程序需要在bla bla bla短语中计数,并以此特定顺序返回单词及其计数。
Any Help? 有帮助吗?
Your count
function is not used correctly. 您的
count
功能使用不正确。 You want text.search(vowel)
, not vowel.search(text)
您想要
text.search(vowel)
,而不是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
. 您正在计算每个元音出现在
vowels
。
Replace with text.count(i)
instead of vowels.count(i)
. 替换为
text.count(i)
而不是vowels.count(i)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.