ここに良い例があります:
>>> 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
>>>
count
orは使用していませんcount2
が、すべてのオカレンスを置き換えたいと思います。私の例ではファイルではなくテキストを使用しているため、必要なものは次のとおりです。
with open(outputfile, 'w') as output:
with open(file, 'r+') as book:
for line in book:
output.write(pattern.sub(translate, line))