0

I want to use make replacements on a text file which is

one two three pthree two ptwo one two ...(1000+ words)

such that output looks like 1 2 3 p3 2 p2 1 2 ....

My code looks like

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)

I have tried these solutions str.replace and regex but both methods give me the same error which is

TypeError: replace() argument 2 must be str, not int

What does this error mean? And how should I resolve it? Thank You

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
pro_nav
  • 23
  • 1
  • 4
  • 4
    The code you posted works without any errors though. – bereal Oct 09 '20 at 08:51
  • Yep, seems to be working, see https://repl.it/@ChristianBauman/WoozyAggressiveUnix – Christian Baumann Oct 09 '20 at 08:54
  • `TypeError: replace() argument 2 must be str, not int` Well this error just tells you that you need to put in a `str` type but you are giving it `int`. Try first converting it to `str` using `str()` function. Probably you're not just providing much details on your question. – Ice Bear Oct 09 '20 at 08:56
  • 1
    Also, it replaces every occurance. For ex: `'phone'` will be `'ph1'`, which you might not be anticipating. – Austin Oct 09 '20 at 08:57

1 Answers1

1

Running the code you have written in the question actually works. From the error I suspect that the dictionary you are actually working against is more like:

{ 'zero': 0, 'one': 1 } # etc

I.E the values are integers rather than strings. You can either correct whatever is creating the dictionary to ensure that the values have the right type, or you can cast to the correct type before calling replace

d = { 'zero': 0, 'one': 1, 'two': 2, 'three': 3 }
x = 'one two three pthree two ptwo one two' #reading input from file
for k, v in d.items():
    x = x.replace(k, str(v))
xulaus
  • 73
  • 3