I'm trying to automate a series of find/replace actions. I have an input file containing a large list of stemmed verb forms like this:
apolog
apologis
becam
apologis
apologis
apologis
apologis
becom
becom
aris
arisen
arisen

I want to change every "apologis" to "apolog", every "arisen" to "aris" and so on. Since my set of changes is large, I created a csv file containing a list of old forms and new forms like this:
apologis,apolog
arisen,aris
author,authoris
beaten,beat
becom,becam
capitalis,capit
categoris,categor

Now I've written a script that I thought would iterate through each csv entry, and make replacements in the target file, but it just prints the original file with no changes. Here's my code:

import string, sys, os
from os.path import join
import csv

myFile = open("input.csv","r")
x = "".join(myFile)

changes = csv.reader(open('test2_stext_rtext.csv', 'rb'))

for old, new in changes:
        replaced_verb = x.replace(old, new)

print replaced_verb
myFile.close()

If I take this code and put a specific string in, it works (just for that string), like this:

for old, new in changes:
replaced_verb = x.replace('aplogis', 'aplog')

So the problem seems to be to get Python to take each old and new form properly. Any suggestions would be appreciated.

Variable myFile is just file handle, what do you expect join() would do to it?

I expect it to take the file object “myFile” and turn it into a string object “x” so that the .replace method will work. Perhaps there is a better way to do this.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.