[Python] Text file Converter (replacing unknown words)

Discussão em 'Python' iniciado por Stack, Maio 13, 2025.

  1. Stack

    Stack Membro Participativo

    I started playing with Python and programming in general like 3 weeks ago so be gentle ;)

    What i try to do is convert text files the way i want them to be, the text files have same pattern but the words i want to replace are unknown. So the program must first find them, set a pattern and then replace them to words i want.

    For example:
    xxxxx
    xxxxx
    Line3 - word - xxxx xxxx
    xxxxx xxxx
    word
    word
    xxxx word

    Legend:
    xxxxx = template words, present in every file
    word = random word, our target


    I am able to localize first apperance of the word because it appears always in the same place of the file, from then it appears randomly.

    MY code:


    f1 = open('test.txt', 'r')
    f2 = open('file2.txt', 'w')

    pattern = ''
    for line in f1.readlines():
    if line.startswith('Seat 1'):
    line = line.split(' ', 3)
    pattern = line[2]
    line = ' '.join(line)
    f2.write(line)
    elif pattern in line.strip():
    f2.write(line.replace(pattern, 'NewWord'))
    else:
    f2.write(line)
    f1.close()
    f2.close()


    This code doesnt work, whats wrong ?

    Continue reading...

Compartilhe esta Página