【发布时间】:2021-01-24 08:10:43
【问题描述】:
我想在一个文本文件上使用 make 替换
one two three pthree two ptwo one two ...(1000+ words)
这样的输出看起来像1 2 3 p3 2 p2 1 2 ....
我的代码看起来像
dict = { 'zero':'0','one':'1','two':'2','three':'3','four':'4','five':'5','six':'6','seven':'7'}
x = 'one two three pthree two ptwo one two' #reading input from file
for k, v in dict.items():
x = x.replace(k, v)
我已经尝试过str.replace 和regex 这些解决方案,但是这两种方法都给了我同样的错误
TypeError: replace() argument 2 must be str, not int
这个错误是什么意思?我应该如何解决它? 谢谢你
【问题讨论】:
-
您发布的代码没有任何错误。
-
是的,似乎工作正常,请参阅repl.it/@ChristianBauman/WoozyAggressiveUnix
-
TypeError: replace() argument 2 must be str, not int这个错误只是告诉你需要输入str类型,但你给它的是int。首先尝试使用str()函数将其转换为str。可能您不只是提供有关您的问题的详细信息。 -
另外,它会替换每一次出现。例如:
'phone'将是'ph1',您可能没有预料到。