首页 > 解决方案 > for 循环内的字典未按预期工作 TypeError:replace() 至少需要 2 个参数(给定 1 个)

问题描述

我正在尝试用完整的单词替换缩写词。例如替换causebecause. 但是我得到一个错误。这里的收缩是我的字典,我正在尝试创建一个函数,该函数将从收缩字典中获取单词并用值替换键。例如,原因是键,因为是值等。

字典

contraction = {'cause':'because',
              'aint': 'am not',
              'aren\'t': 'are not'}

定义函数来用完整的词替换像cause、arent这样的词——因为和不是等。

def mapping_replacer(x,dic):
    for words in dic.keys():
        if ' ' + words + ' ' in x:
            x=x.replace(' '+ words +' ' ' '+dic[words]+' ' )
    return x

调用函数。train 是具有列内容的数据库。我想找到像原因这样的词,不是来自火车的内容列,并将它们替换为因为,不是等。

train['content']=train['content'].apply(lambda x: mapping_replacer(x, contraction))

错误

  <ipython-input-122-4f7429b148ac> in mapping_replacer(x, dic)
      6     for words in dic.keys():
      7         if ' ' + words + ' ' in x:
----> 8             x=x.replace(' '+ words +' ' ' '+dic[words]+' ' )
      9     return x
     10 

TypeError: replace() takes at least 2 arguments (1 given)

标签: pythonpandas

解决方案


您缺少要替换的第二个参数。

x = x.replace(' '+ words +' ' ' '+dic[words]+' ' )

我猜你应该放这个。

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

推荐阅读