Python:文本文件中特定单词后的换行符

Python:文本文件中特定单词后的换行符,python,Python,我有一个文本文件,只有一行10.000字。 现在,我想在出现特定单词(“注释”)之前添加一个换行符,并将其写入新的文本文件: 文本文件看起来像:“注释:是的,你说得对注释:那很有趣注释:真的吗 新文件应该如下所示: Comment: Yeah, you're right Comment: That's very interesting Comment: really? 我尝试了下面的代码,但出现了一些问题。我是一个初学者,直到现在,我还没有找到解决方案。谢谢你的帮助

我有一个文本文件,只有一行10.000字。 现在,我想在出现特定单词(“注释”)之前添加一个换行符,并将其写入新的文本文件:

文本文件看起来像:“注释:是的,你说得对注释:那很有趣注释:真的吗

新文件应该如下所示:

    Comment: Yeah, you're right
    Comment: That's very interesting
    Comment: really?
我尝试了下面的代码,但出现了一些问题。我是一个初学者,直到现在,我还没有找到解决方案。谢谢你的帮助

    -*- coding: utf-8 -*-

    d = file('test.txt','r')
    text=d.read()
    e = file('output.txt','w')
    x=raw_input("Insert word:")
    # -> Comment
    for line in d.readlines():
          if line.startswith(x):
            word.append(+"\n")
            e.write()
            e.close()
            d.close()

您只需要使用str.replace:

e.write(d.read().replace(' Comment:', '\nComment:'))

一个非常简单的解决方案可以是:

for line in d.readlines():
    e.write(line.replace("Comment:",  "\nComment:"))

e.close()    

您可以执行
'\n'。将(x+':'+字符串连接到第行的字符串中。拆分(x+':')

以下是错误的解释,顺序如下:

d = file('test.txt','r')
text=d.read() # Ok: now 'text' contains the entire file contents.
e = file('output.txt','w')
x=raw_input("Insert word:")
# -> Comment
for line in d.readlines(): # You already read the whole file, so
# this loop can't read any more. But even without that, your input
# file only contains one line, so this would only loop once.
      if line.startswith(x): # You are trying to look for a word at the
      # beginning of each line, in order to determine where to put the
      # line breaks. But the words can't be found at the beginnings of
      # all the lines until those lines exist, i.e. after the line 
      # breaks have been positioned.
        word.append(+"\n") # This makes no sense at all. You can't 
        # '.append' to 'word' because there is no 'word' defined yet,
        # and '+"\n"' is trying to treat a string like a number. Yes,
        # you can use '+' to join two strings, but then you need one
        # on either side of the '+'. 1 + 1, "hi " + "mom".
        e.write() # If you want to write something to the file, you have
        # to specify what should be written.
        e.close() # If the loop *did* actually execute multiple times,
        d.close() # then you definitely wouldn't want to close the files
        # until after the loop is done.

其他答案解释了如何正确处理该问题。我们将文件读入字符串,并在单词的每个外观之前添加换行符。这相当于将单词的每个外观替换为(换行符,后跟单词)。该功能是内置的。然后,我们将修改后的字符串写入输出文件。

有几件事我没有从您的代码中得到。首先,如果您的输入文件只有一行,为什么要使用readlines()?您的输入文件只有一行,因此d.readlines()将在您第一次调用它时返回文件的全部内容。