[英]Text file Converter (replacing unknown words)
I started playing with Python and programming in general like 3 weeks ago so be gentle;)我开始玩 Python 并像 3 周前一般编程,所以要温和;)
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!欢迎来到 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.我相信您走在正确的轨道上并且非常接近正确的解决方案,但是我看到了一些可能导致您的程序无法按预期运行的潜在问题。
==
instead of is
(see this answer for more info)==
而不是is
(有关更多信息,请参见此答案)\n
which means your variable line
might never match your word.\n
结尾,这意味着您的可变line
可能永远不会匹配您的单词。 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:
with
statement that Python provides (see question and/or tutorial )with
语句(参见问题和/或教程) 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我看到你可能将单词 be 包含在该行中,而不是按照第 1 点中的建议使用
==
,你可以使用 in,但你需要颠倒顺序,即
elif pattern in line:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.