为啥我收到此错误? KeyError:“没有”

Posted

技术标签:

【中文标题】为啥我收到此错误? KeyError:“没有”【英文标题】:why I am getting this error ? KeyError: "Didn't"为什么我收到此错误? KeyError:“没有” 【发布时间】:2016-06-09 01:53:46 【问题描述】:

我正在使用来自Expanding English language contractions in Python 的 Alko 代码

我添加了一些代码。我不明白为什么我会得到这个 =>KeyError: "没有"

import re
import csv
fileLocation = 'test.csv'
cList = 
  "ain't": "am not",
  "aren't": "are not",
  "can't": "cannot",
  "can't've": "cannot have",
  "'cause": "because",
  "could've": "could have",
  "couldn't": "could not",
  "couldn't've": "could not have",
  "didn't": "did not",
  "doesn't": "does not",

        
R = re.compile('(%s)' % '|'.join(cList.keys()),re.IGNORECASE)
read = csv.reader(open(fileLocation))
aList = []
def expandContractions(text,R=R):
    def replace(match):
        return cList[match.group(0)]
    return R.sub(replace, text)    
for i in read:
    aList.append(i[5])
for j in aList:
    print(expandContractions(j))

【问题讨论】:

print(expandContractions(j.lower())) 【参考方案1】:

不要使用re.IGNORECASE 在你的键上使用.lower(),要么总是小写你的输入字符串:

return R.sub(replace, text.lower())expandContractions;或 print(expandContractions(j.lower()))

或将大写和标题大小写的可能性添加到您的 cList 字典中:

cList = 
...
'DID NOT': "DIDN'T"
'Did not': "Didn't"
...

您做出何种选择取决于您想对产生的收缩做什么,以及您想如何处理完全混乱的情况,例如"dId NOt"

【讨论】:

以上是关于为啥我收到此错误? KeyError:“没有”的主要内容,如果未能解决你的问题,请参考以下文章

为啥我会收到此错误?返回标签错误(页面没有链接回来)

KeyError:“文件名”(熊猫)

为啥我收到此错误“没有构造函数实例”,CUDA 优化器中的 viennacl 库,C++ 控制台应用程序

如何使用 Flask-SocketIO 修复此 KeyError 错误?

为啥我在此代码中收到 SIGABRT 错误 [关闭]

谁能告诉我为啥我从 GitLab 收到此“错误:作业失败:退出代码 1”消息?