我有一个函数应该返回包含每个元音(全部小写)的单词数,但我不断收到键错误。我很感激任何帮助。谢谢。
def vowelUseDict(t):
'''computes and returns a dictionary with the number of words in t containing each vowel
'''
vowelsUsed = {}
strList = t.split()
newList = []
vowels ='aeiou'
for v in vowels:
for strs in strList:
if v in strs and strs not in newList:
newList.append(strs)
vowelsUsed[v] = 1
if v in strs and strs in newList:
vowelsUsed[v] += 1
return vowelsUsed
text = 'like a vision she dances across the porch as the radio plays'
print(vowelUseDict(text))
#{'e': 5, 'u': 0, 'o': 4, 'a': 6, 'i': 3}
答案 0 :(得分:0)
from collections import Counter
def vowelUseDict(t):
vowels = 'aeiou'
cnt = sum(map(Counter, t.split()), Counter())
return {k: cnt[k] if k in cnt else 0 for k in vowels}
答案 1 :(得分:0)
那是因为newList
保留了之前元音中的单词。一旦你到达"喜欢"对于" i",它已经存在,因为它被添加到" e"。这意味着它会尝试添加键值#34; i"在vowelsUsed
中,它不存在(它会在第一次找到一个单词时添加,但是没有为另一个元音添加)。
由于(从最后一行判断)你希望每个元音都在最终的dict中,你可以创建dict,所有的元音都是键,值是0,你甚至不必检查密钥是否存在。如果单词包含元音,只需将值增加一。
结果代码如下:
def vowelUseDict(t):
'''computes and returns a dictionary with the number of words in t containing each vowel
'''
strList = t.split()
vowels ='aeiou'
vowelsUsed = {v: 0 for v in vowels}
for v in vowels:
for strs in strList:
if v in strs:
vowelsUsed[v] += 1
return vowelsUsed
text = 'like a vision she dances across the porch as the radio plays'
print(vowelUseDict(text))
#{'e': 5, 'u': 0, 'o': 4, 'a': 6, 'i': 3}
罗伊·奥比森为孤独而歌唱;嘿,那是我和我只想要你