2011-08-29 80 views
3

我有一个文本文件,并有一个与10.000话只是一个行后打破。 现在我想在出现特定单词(“评论”)之前添加换行符,并且我还希望将其写入新的文本文件中:的Python:行一个文本特定单词

该文本文件类似于:“注释:是的,您说得对评论:这是非常有趣的评论:真的吗?

而新的文件应该是这样的:。

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() 
+1

有几件事我没有从你的代码中得到。首先,如果你的输入文件只有一行,你为什么使用readlines()? –

+0

您的输入文件只是一条巨大的线,所以d.readlines()将在第一次调用时返回文件的全部内容。 –

回答

5

你只需要使用str.replace:

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

一个非常简单的解决办法是:

0

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

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. 

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

相关问题