here is a good example:
>>> import re
>>> set1 = ['word1','word2','word3']
>>> set2 = ['new_word1','new_word2','new_word3']
>>> translation = dict(zip(set1, set2))
>>>
>>>
>>> text = '''
... here I am word1 talking about word2.
... ipsum ipsumipsum ipsum ipsum ipsum ipsum ipsum
... ipsum ipsumipsum word1 ipsum ipsum ipsum ipsum
... ipsum ipsumipsum ipsum ipsum word2 ipsum ipsum
... ipsum ipsumipsum ipsum ipsum ipsum ipsum ipsum
... '''
>>>
>>> # compile a pattern matching any of the words
... pattern = re.compile('(%s)' % '|'.join(set1))
>>>
>>> def translate(match):
... return translation[match.group(0)]
...
>>> # replace with: for line in book:
>>> for line in text.splitlines():
... print pattern.sub(translate, line)
...
here I am new_word1 talking about new_word2.
ipsum ipsumipsum ipsum ipsum ipsum ipsum ipsum
ipsum ipsumipsum new_word1 ipsum ipsum ipsum ipsum
ipsum ipsumipsum ipsum ipsum new_word2 ipsum ipsum
ipsum ipsumipsum ipsum ipsum ipsum ipsum ipsum
>>>
I am not using count
or count2
though, I assumed you want to replace all occurences.
Since I am using text in my example and not a file here is what you need:
with open(outputfile, 'w') as output:
with open(file, 'r+') as book:
for line in book:
output.write(pattern.sub(translate, line))