函数中的Python键错误

函数中的Python键错误,python,Python,我有一个函数,该函数应该返回包含每个元音的单词数(全部小写),但我不断得到一个键错误。如果能帮我弄清楚,我将不胜感激。多谢各位 def vowelUseDict(t): '''computes and returns a dictionary with the number of words in t containing each vowel ''' vowelsUsed = {} strList = t.split() newList = []

我有一个函数,该函数应该返回包含每个元音的单词数(全部小写),但我不断得到一个键错误。如果能帮我弄清楚,我将不胜感激。多谢各位

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}

这是因为
newList
保留了以前元音中的单词。一旦你达到“i”的“like”,它就已经存在了,因为它是为“e”添加的。这意味着它试图添加到
元音使用中的键“i”的值,该值不存在(在第一次发现没有为另一个元音添加的单词时,会添加该值)

因为(从最后一行判断)您希望每个元音都在结果dict中,所以您可以创建一个dict,将所有元音都作为键,值为零,甚至不必检查键是否存在。如果单词包含元音,只需将值增加1即可

生成的代码如下所示:

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}

罗伊·奥比森为孤独者歌唱;嘿,那是我,我只想要你

我会使用defaultdict或集合中的计数器。这将简化这一混乱局面……你知道什么是关键错误吗?并检查/打印except套件中的数据。它应该给你一个正在发生的事情的想法-从那里向后工作。
元音使用的[v]+=1
可能是产生错误的语句
v
不能是密钥。这意味着如果strs中的v和newList中的strs中的v存在一个条件
错误:
@wwii yes,那么保存该错误的collections.Counter对象就是错误的logic@Jean-弗朗索瓦·法布。。。除非目的是学习如何将逻辑转换为代码。
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}