【发布时间】:2020-06-26 08:02:01
【问题描述】:
我正在尝试用完整的单词替换缩写词。例如用因为替换原因。但是我得到一个错误。这里的收缩是我的字典,我正在尝试创建一个函数,该函数将从收缩字典中获取单词并用值替换键。例如Cause 是键,因为是值等。
字典
contraction = {'cause':'because',
'aint': 'am not',
'aren\'t': 'are not'}
定义函数来用完整的词替换像cause,arent这样的词 - 因为和不是等。
def mapping_replacer(x,dic):
for words in dic.keys():
if ' ' + word + ' ' in x:
x=x.replace(' '+ word +' ' ' '+dic[word]+' ' )
return x
调用函数。 train 是一个具有列内容的数据库。我想找到像原因这样的词,不是来自火车的内容列,并将它们替换为因为,不是等。
train['content']=train['content'].apply(lambda x: mapping_replacer(x, contraction))
错误
NameError Traceback (most recent call last)
<ipython-input-121-4265efab94f1> in <module>
----> 1 train['content']=train['content'].apply(lambda x: mapping_replacer(x, contraction))
<ipython-input-109-f0798b6d0ea8> in mapping_replacer(x, dic)
5 def mapping_replacer(x,dic):
6 for words in dic.keys():
----> 7 if ' ' + word + ' ' in x:
8 x=x.replace(' '+ word +' ' ' '+dic[word]+' ' )
9 return x
NameError: name 'word' is not defined
【问题讨论】:
-
将
word更改为words,因为您提到的 for 循环变量为words -
一般ain't可以映射到所有am not、is not、和are not . 你需要更多的上下文来决定在每种情况下哪个是正确的。
-
暂时将其视为编码问题。