简体   繁体   English

文本文件转换器(替换生词)

[英]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.我相信您走在正确的轨道上并且非常接近正确的解决方案,但是我看到了一些可能导致您的程序无法按预期运行的潜在问题。

  1. If you are trying to see if a string equals another, I would use == instead of is (see this answer for more info)如果您想查看一个字符串是否等于另一个字符串,我会使用==而不是is (有关更多信息,请参见此答案)
  2. When reading a file, lines end with \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)要解决此问题,您可以使用 strip,它会自动删除前导和尾随的“空格”字符(如空格或换行符)
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 )处理文件时,强烈建议使用 Python 提供的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.

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