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

时间:2011-08-29 21:54:26

标签: 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()

4 个答案:

答案 0 :(得分:5)

你只需要使用str.replace:

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

答案 1 :(得分:1)

以下是对错误的解释:

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.

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

答案 2 :(得分:0)

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

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

e.close()    

答案 3 :(得分:0)

你可以'\n'.join(x+': '+string for string in line.split(x+': '))