python - for 循环内的字典未按预期工作 TypeError:replace() 至少需要 2 个参数(给定 1 个)
问题描述
我正在尝试用完整的单词替换缩写词。例如替换cause
为because
. 但是我得到一个错误。这里的收缩是我的字典,我正在尝试创建一个函数,该函数将从收缩字典中获取单词并用值替换键。例如,原因是键,因为是值等。
字典
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)
解决方案
您缺少要替换的第二个参数。
x = x.replace(' '+ words +' ' ' '+dic[words]+' ' )
我猜你应该放这个。
x = x.replace(' ' + words + ' ', ' ' + dic[words] + ' ')
推荐阅读
- ios - SceneKit 创建 2d 世界
- sql - SQL 使用两列过滤记录
- javascript - 如何在 vuex 中将对象键/值对设置为初始状态
- javascript - 为什么 cancelAnimationFrame () 不会在 MouseDown 事件上停止动画?
- java - Junit Mockito:Void 函数和 RestTemplate 调用模拟
- c# - C# Socket BeginSend BeginReceive 导致断开操作
- sql-server - SQL配置具有域用户模拟的链接服务器 - kerberos /委派要求?
- java - Hibernate:对两个不同的类使用一个表
- python - AWS Lambda 错误消息“无法导入模块‘lambda_function’:没有名为‘lambda_function’的模块”,
- c# - 带有徽标的选中列表框项目