简体   繁体   English

Python KeyError:使用字典和函数时为0

[英]Python KeyError: 0 when working with dictionary and functions

I'm new to Python so my question may seem easy to some but then again I'm stuck on my own so I need your help! 我是Python的新手,所以我的问题在某些人看来似乎很简单,但是我又一次陷入了困境,因此我需要您的帮助! This is the code that i am having trouble with: 这是我遇到麻烦的代码:

def identify_language(sequence, **common_words):
    result = {}
    for i in common_words:            
        result[i] = 0
    for i in func_op(sequence.lower()):
        for j in common_words:
            if i in common_words[j]:
                result[j] += 1
    return sort(result[0][0])

...

dictionary = {'cro':list_cro, 'eng':list_cro}
language = identify_language('I had a little lamb. It was called Billy.', **dictionary)

I am trying to identify language based on samples which are in list_cro and list_eng (and hopefully others). 我正在尝试根据list_crolist_eng (并希望其他人)中的示例识别语言。 I am getting KeyError: 0 . 我收到KeyError: 0 Additionally, sort and func_op are working fine i tested then separately. 另外, sortfunc_op运行良好,我分别进行了测试。 What may be the problem? 可能是什么问题?

Also, if i change order of arguments in function (putting list as a first argument and string as second) i am getting syntax error. 另外,如果我更改函数中参数的顺序(将列表作为第一个参数,将字符串作为第二个参数),则会收到语法错误。 Thanks for listening! 谢谢收听!

At the end of the function, result should look like this: {'cro': X, 'eng': Y} , where X and Y are numbers. 在函数末尾, result应如下所示: {'cro': X, 'eng': Y} ,其中X和Y是数字。 I don't know what your dictionaries are, so I can't guess what the numbers are. 我不知道您的词典是什么,所以我猜不出数字是多少。 Evaluating result['eng'] will produce a number, as will result['cro'] , but there is no 0 key in this dictionary. 计算result['eng']会产生一个数字, result['cro'] result['eng']也会产生一个数字,但是此字典中没有0键。

Further, the second indexing operation will also give you issues. 此外,第二次索引操作也会给您带来问题。 result['eng'][0] will give you an error because result['eng'] is a number, and you can't index into a number. result['eng'][0]将给您一个错误,因为result['eng']是一个数字,并且您无法索引到数字。

What do you expect the output of this function to look like? 您期望此函数的输出看起来如何? Where is sort defined and what is it supposed to do? 在哪里定义sort ,应该做什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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