Replacing words in text file using a dictionary

David Manning picture David Manning · Mar 31, 2017 · Viewed 8.7k times · Source

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 in Python? I could pull out the dictionary values before doing the replacing, but looping through the dictionary seems more efficient.

The code doesn't produce any errors, but also doesn't do any replacing.

import fileinput

text = "sample file.txt"
fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"}

for line in fileinput.input(text, inplace=True):
    line = line.rstrip()
    for i in fields:
         for field in fields:
             field_value = fields[field]

             if field in line:
                  line = line.replace(field, field_value)


             print line

Answer

Kruupös picture Kruupös · Mar 31, 2017

I used items() to iterate over key and values of your fields dict.

I skip the blank lines with continue and clean the others with rstrip()

I replace every keys found in the line by the values in your fields dict, and I write every lines with print.

import fileinput

text = "sample file.txt"
fields = {"pattern 1": "replacement text 1", "pattern 2": "replacement text 2"}


for line in fileinput.input(text, inplace=True):
    line = line.rstrip()
    if not line:
        continue
    for f_key, f_value in fields.items():
        if f_key in line:
            line = line.replace(f_key, f_value)
    print line