【问题标题】:NameError: name 'word' is not defined while defining for loop to take values from dictionary [closed]NameError:在定义for循环以从字典中获取值时未定义名称'word'[关闭]
【发布时间】: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 notis not、are not . 你需要更多的上下文来决定在每种情况下哪个是正确的。
  • 暂时将其视为编码问题。

标签: python pandas


【解决方案1】:

我认为你必须使用for word in dic.keys():,而不是words

还要检查替换语句中缺少的,

 x=x.replace(' '+ word +' ', ' '+dic[word]+' ' )

【讨论】:

  • 现在错误是:TypeError: replace() 需要至少 2 个参数(1 个给定)
  • &lt;ipython-input-122-4f7429b148ac&gt; in mapping_replacer(x, dic) 6 for words in dic.keys(): 7 if ' ' + words + ' ' in x: ----&gt; 8 x=x.replace(' '+ words +' ' ' '+dic[words]+' ' ) 9 return x 10 TypeError: replace() takes at least 2 arguments (1 given)
  • @ShailajaGuptaKapoor 你想替换什么?这是实际语法replace(replace_word, 'replace_by ')
  • 我只是想用because替换像cause这样的词,用are not替换像aren't这样的词
  • replace 的参数之间缺少逗号。 Python——或者我们,你的读者——应该如何知道哪些字符串片段是要替换的字符串的一部分,如果你不将它们分开,哪些构成了替换?还要记住,两个相邻的字符串 'a' 'b' 在语法上等价于它们在 Python 中的串联 'ab'
猜你喜欢
  • 2016-08-01
  • 1970-01-01
  • 2021-08-23
  • 1970-01-01
  • 2016-12-20
  • 2023-03-05
  • 2020-12-23
  • 2014-03-18
  • 2021-07-27
相关资源
最近更新 更多