为什么我得到这个错误? KeyError:“没有”
问题描述:
我使用Alko的代码Expanding English language contractions in Python为什么我得到这个错误? KeyError:“没有”
我添加了一个位代码。我不明白为什么我收到此=> 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))
答
而不是使用re.IGNORECASE
和使用在你的钥匙.lower()
的,要么始终小写的输入字符串:
-
return R.sub(replace, text.lower())
inexpandContractions
;或 print(expandContractions(j.lower()))
或大写和标题的情况下可能添加到您的CLIST词典:
cList = {
...
'DID NOT': "DIDN'T"
'Did not': "Didn't"
...
}
哪一个选项,你让取决于你想要得到的收缩,做什么,以及如何处理完全混乱的案例,如。
'print(expandContractions(j.lower()))' – alvas
谢谢alvas。有用 – danny