replace multiple words using python

This is the place for queries that don't fit in any of the other categories.

replace multiple words using python

Postby lmr1405 » Thu Nov 07, 2013 6:58 am

HI I am trying to replace words using python:

I have the following script:

Code: Select all
####open_file
import codecs
input_file=codecs.open("corpus3_tst","r",encoding="utf-8")
lines=input_file.readlines()
for line in lines:
    line=line.rstrip()
    print line
   
    # define method
def replace_all(text, dic):
    for i, j in dic.iteritems():
        text = text.replace(i, j)
    return text
 
# text for replacement
my_text = line

# dictionary with  key:values.
# replace values
reps = {'dog':'ANIMAL', 'cat':'ANIMAL', 'pigeon':'ANIMAL'}
print reps

# bind the returned text of the method
# to a variable and print it
txt = replace_all(my_text, reps)
print txt       


My input text looks like this:

Code: Select all
dog   walk   1
cat   walk   2
piegon   bark 3


However, the script only prints out the last line. -- and is not replacing anything...

This is the result, I am getting.

Code: Select all
piegon   bark   3


Any insight to how I can fix this?
Thank you
Last edited by lmr1405 on Thu Nov 07, 2013 9:44 am, edited 1 time in total.
lmr1405
 
Posts: 22
Joined: Fri Oct 25, 2013 9:49 am

Re: replace multiple words using pythong

Postby Kebap » Thu Nov 07, 2013 9:22 am

lmr1405 wrote:the script only prints out the last line.

This is because your "for line in lines" has already ended way earlier. After that, you only look at the last line.

lmr1405 wrote: and is not replacing anything...

This is solely because "piegon" is not in your dictionary.
Learn: How To Ask Questions The Smart Way
Join the #python-forum IRC channel on irc.freenode.net and chat with uns directly!
Kebap
 
Posts: 282
Joined: Thu Apr 04, 2013 1:17 pm
Location: Germany, Europe

Re: replace multiple words using pythong

Postby lmr1405 » Thu Nov 07, 2013 9:42 am

You are right:

Also, here is the updated "working" code:

changing this line:
Code: Select all
lines=input_file.readlines()
for line in lines:
    line=line.rstrip()

to

Code: Select all
words = input_file.read().rstrip()



Thanks!
lmr1405
 
Posts: 22
Joined: Fri Oct 25, 2013 9:49 am


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 8 guests

cron