简体   繁体   中英

Text file Converter (replacing unknown words)

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?

welcome to the world of Python!

I believe you are on the right track and are very close to the correct solution, however I see a couple of potential issues which may cause your program to not run as expected.

  1. If you are trying to see if a string equals another, I would use == instead of is (see this answer for more info)
  2. When reading a file, lines end with \n which means your variable line might never match your word. To fix this you could use strip, which automatically removes leading and trailing "space" characters (like a space or a new line character)
elif line.strip() == pattern:
  1. This is not really a problem but a recommendation, since you are just starting out. When dealing with files it is highly recommended to use the with statement that Python provides (see question and/or tutorial )

Update:

I saw that you might have the word be part of the line, do instead of using == as recommended in point 1, you could use in, but you need to reverse the order, ie

elif pattern in line:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM