【发布时间】:2022-11-25 20:26:40
【问题描述】:
我大约在 3 周前开始玩 Python 和编程,所以要温柔点;)
我尝试做的是按照我希望的方式转换文本文件,文本文件具有相同的模式,但我想替换的词是未知的。所以程序必须首先找到它们,设置一个模式然后将它们替换为我想要的单词。
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
我能够本地化单词的第一次出现,因为它总是出现在文件的同一个地方,从那时起它随机出现。
我的代码:
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()
这段代码不起作用,怎么了?
【问题讨论】:
标签: python text replace converters