【问题标题】:KeyError when key exists in dictionary字典中存在键时出现KeyError
【发布时间】:2020-05-20 14:05:33
【问题描述】:

我正在编写一个检测推文语言并应用与该语言匹配的词法的代码。使用的代码工作得很好,它完成了它的工作。然后它抛出了一个KeyError: 'en',即使字典中存在'en'。我查看了多个已经有答案的问题,但似乎没有任何效果。我将提供仅处理德语的代码部分(因此不包括其他语言)。如果检测到的语言不在字典中,代码会写入到哪里,它会自动归类为英语。

from langdetect import detect
import glob
import re

rsc_lg = {
      "de" : {"pos" : "ressources/positive_words_de.txt",
              "neg" : "ressources/negative_words_de.txt"},
      "en" : {"pos" : "ressources/positive_words_en.txt",
              "neg" : "ressources/negative_words_en.txt"}
      }
dic = {}
liste_resultats = []
for path in glob.glob("corpus/*/*/*"):
  f = open(path, errors="ignore")
  read = f.read().lower()
  lang = detect(read)
  if lang not in dic:
    dic[lang] = {} 

  if lang not in rsc_lg :
    lang = "en"

###german###
  f_de_pos = open(rsc_lg[lang]["pos"])
  f_de_neg = open(rsc_lg[lang]["neg"])
  de_pos = f_de_pos.read().lower().split()
  de_neg = f_de_neg.read().lower().split()
  f_de_pos.close()
  f_de_neg.close()

  words = read.split()
  pos_words_de = set(words) & set(de_pos)
  neg_words_de = set(words) & set(de_neg)

  if len(pos_words_de) > len(neg_words_de):
      diagnostic = "positive"
  if len(pos_words_de) == len(neg_words_de):
      diagnostic = "mixed"
  if len(pos_words_de) < len(neg_words_de):
      diagnostic = "negative"
#  print("this german tweet is ", diagnostic)
  dic[lang][path] = diagnostic


  corpus, lang, classe, nom = re.split("\\\\", path)
  liste_resultats.append([nom, lang, classe, diagnostic])

import json
w = open("resultats_langdetect_german.json", "w")
w.write(json.dumps(liste_resultats, indent= 2))
w.close()

f.close()

print("done")

错误出现在将推文分类为正面、混合或负面之后的dic[lang][path] = diagnostic 行。 就像我说的,尽管我完全没有对代码进行任何更改,但它之前工作得很好,但突然停止工作。

【问题讨论】:

  • 你调试过这段代码吗?错误是在哪一行抛出的?
  • 你让我们猜测错误在哪里。请更新问题以包含完整的错误回溯消息。
  • 糟糕,对不起!我已经添加了错误发生的位置

标签: python dictionary keyerror


【解决方案1】:

问题是如果遇到未知语言,则执行dic[lang] = {},然后立即执行lang = "en"。现在,如果lang 是例如"es",那么您最终会得到dic == {"es": {}}lang == "en"。稍后在代码中执行dic[lang][path] = diagnostic 但此时"en" not in dic 因为它仍然使用未知语言代码("es")。您可能想切换两个语句的顺序,即先设置lang = "en",然后再执行dic[lang] = {}

【讨论】:

  • 谢谢,我什至没有想到这一点。奇怪之前还好好的,突然发现有错误!
  • @ArieG。这可能是因为您在一些新数据上运行了代码,这些数据被检测为一种未包含在您的资源中的语言。这就是它可以在不改变代码本身的情况下改变行为的方式,它依赖于输入数据。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-15
  • 2017-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-09
相关资源
最近更新 更多