+-
Python:特定单词后的文本文件中的换行符
我有一个文本文件,只有一行有10.000个单词.
现在我想在特定单词(“Comment”)出现之前添加换行符,我还想在新的文本文件中写这个:

文本文件看起来像:“评论:是的,你是对的评论:这是非常有趣的评论:真的吗?

新文件应如下所示:

    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:'))
点击查看更多相关文章

转载注明原文:Python:特定单词后的文本文件中的换行符 - 乐贴网