![](/img/trans.png)
[英]Python3 - Extracting data from a user inputted string. Could be in the wrong format
[英]Python, counting from an inputted string. Needs to be returned in a specific order?
因此,我正在输入用户需要输入>> Count('bla bla bla')的代码,程序需要在bla bla bla短语中计数,并以此特定顺序返回单词及其计数。
有帮助吗?
您的count
功能使用不正确。 您想要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}
字典没有顺序,因此如果要按元音顺序计数:
>>> [(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')
希望这可以帮助。
您输入错误:
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.'
编写的代码甚至根本不检查输入文本。 您正在计算每个元音出现在vowels
。
替换为text.count(i)
而不是vowels.count(i)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.