I\'m trying to open a text file and then read through it replacing certain strings with strings stored in a dictionary.
Based on answers to How do I edit a text file
If you can find a regex pattern covering all your keys, you could use re.sub
for a very efficient solution : you only need one pass instead of parsing your whole text for each search term.
In your title, you mention "replacing words". In that case, '\w+'
would work just fine.
import re
fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"}
words_to_replace = r'\bpattern \d+\b'
text = """Based on answers to How do I edit a text file in Python? pattern 1 I could pull out
the dictionary values before doing the replacing, but looping through the dictionary seems more efficient.
Test pattern 2
The code doesn't produce any errors, but also doesn't do any replacing. pattern 3"""
def replace_words_using_dict(matchobj):
key = matchobj.group(0)
return fields.get(key, key)
print(re.sub(words_to_replace, replace_words_using_dict, text))
It outputs :
Based on answers to How do I edit a text file in Python? replacement text 1 I could pull out
the dictionary values before doing the replacing, but looping through the dictionary seems more efficient.
Test replacement text 2
The code doesn't produce any errors, but also doesn't do any replacing. pattern 3
Also, be very careful when modifying a file in place. I'd advice you to write a second file with the replacements. Once you are 100% sure that it works perfectly, you could switch to inplace=True
.