Replace a string identified in a specific line of a .txt file by another string

Question:

import re, os

def replace_one_line_content_with_other(input_text):
    word_to_replace, replacement_word = "", ""                                                                            

    if (os.path.isfile('data_association/names.txt')):
        word_file_path = 'data_association/names.txt'
    else:
        open('data_association/names.txt', "w")
        word_file_path = 'data_association/names.txt'                                                                        

    #name_capture_pattern = r"([A-Z][wí]+s*(?i:del|des*el|de)s*[A-Z]w+)"
    name_capture_pattern = r"((?:w+))?"
    regex_pattern = r"(?i:nos*es)s*" + name_capture_pattern + r"s*(?i:sinos*ques*es)s*" + name_capture_pattern
 
    n0 = re.search(regex_pattern, input_text)

    if n0: 
        word_to_replace, replacement_word = n0.groups()
        print(repr(word_to_replace))  # --> word that I need identify in the txt
        print(repr(replacement_word)) # --> word by which I will replace the previous one

        #After reaching this point, the algorithm will already have both words, both the one that must be replaced (in case it is identified within the txt) and the one with which it will be replaced.

        numero = None
        with open(word_file_path) as f:
            lineas = [linea.strip() for linea in f.readlines()]
            #Find the word in the .txt file where the words are stored
            if word_to_replace in lineas: numero = lineas.index(word)+1
            #REPLACE   word_to_replace  with  replacement_word  in this .txt line

input_text = "No es Marín sino que es Marina"
replace_one_line_content_with_other(input_text)

After identifying the string stored in the word_to_replace = 'Marín' variable inside the .txt file, I must replace it with the string that is inside the replacement_word = 'Marina' variable.

Original content in the .txt file (it must be assumed that we do not know which line the word is on, so the line number could not be indicated)

Lucy
Martin
Lucila
Samuel
Katherine
María del Pilar
Maríne
Marín
Steve
Robert

And the .txt content after the modification:

Lucy
Martin
Lucila
Samuel
Katherine
María del Pilar
Maríne
Marina
Steve
Robert

Answers:

You can use the sub method of the regex module:

word_to_replace = "Hello"
replacement_word = "Bye"

with open('names.txt', 'r') as names_file_read:
    names = re.sub(word_to_replace, replacement_word, names_file_read.read())

with open('names.txt', 'w') as names_file_write:
    names_file_write.write(names)

This reads every line of the .txt file – and replaces word_to_replace with replacement_word – though not so efficient because we read, delete, and write everything back into place. If your .txt is small it should be good enough. Else, we might want to do the changes only on these specific words in the text, seeking to their position and changing them. I suppose you can use file.readlines() and file.seek() methods.

Answered By: no_hex
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.