簡體   English   中英

Python:特定單詞后的文本文件中的換行符

[英]Python: line break in a textfile after specific word

我有一個文本文件,只有一行有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:'))

以下是對錯誤的解釋:

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.

其他答案解釋了如何正確解決問題。 我們將文件讀入一個字符串,並在每個單詞出現之前添加一個換行符。 這相當於用(換行符,后跟單詞)替換單詞的每個外觀。 該功能是內置的。 然后我們將修改后的字符串寫入輸出文件。

一個非常簡單的解決方案是:

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

e.close()    

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM