簡體   English   中英

在Python 3中打開文件,重新格式化並寫入新文件

[英]Open a file, reformat, and write to a new file in Python 3

我是Python的新手(幾周)。 我正在Coursera上進行Python for Everyone課程,並決定將一些想法擴展到我想編寫的應用程序中。

我想獲取一個寫引號的txt文件,刪除一些不必要的字符和換行符,然后將新格式化的字符串寫到一個新文件中。 該文件將用於在終端中顯示隨機引號(這里不需要后者)。

txt文件中的條目如下所示:

“The road to hell is paved with works-in-progress.”
—Philip Roth, WD some other stuff here
“Some other quote.”
—Another Author, Blah blah

我希望將以下內容寫入新文件:

"The road to hell is paved with works-in-progress." —Phillip Roth
"Some other quote." —Another Author

我想刪除引號和作者之間的換行符並替換為空格。 在作者之后,我還想從逗號中刪除所有內容(所以它就是:quote [space] author)。 該文件有73個,因此我想遍歷文件進行這些更改,然后使用新設置的引號將其寫入新文件。 最終輸出將僅僅是:“等等等等”-作者

我嘗試了各種方法,目前正在for循環中遍歷該文件,將這兩個段寫入到我想加入列表的列表中。 但是我被困住了,也不知道這是否太過分了。 任何幫助將不勝感激。 現在我有了這兩個列表,我似乎無法加入他們的行列,而且我不確定這樣做是否正確。 有什么想法嗎?

到目前為止的代碼:

fh = open('quotes_source.txt')


quote = list()
author = list()

for line in fh:

    # Find quote segment and assign to a string variable
    if line.startswith('“'):
        phrase_end = line.find('”')+1
        phrase_start = line.find('“')
        phrase = line[phrase_start:phrase_end]
        quote.append(phrase)

    # Find author segment and assign to a string variable
    if line.startswith('—'):
        name_end = line.find(',')
        name = line[:name_end]
        author.append(name)

print(quote)
print(author)
quote_line="“The road to hell is paved with works-in-progress.”\n—Philip Roth, WD some other stuff here\n"
quote_line=quote_line.replace("\n","")
quote_line=quote_line.split(",")

formatted_quote=""

如果您不確定該行中只有一個逗號。

  • “一針見血。” \\ n-有人羅斯,等等等等\\ n#只有一個逗號
  • “以牙還牙,以牙還牙” \\ n-某人羅斯,等等等等\\ n#個以上的逗號

     len_quote_list=len(quote_line)-1 for part in range(0,len_quote_list): formatted_quote+=quote_line[part] formatted_quote+="\\n" 

要么

formatted_quote=quote_line[0]+"\n"

您不需要像這樣的簡單任務就使用正則表達式,實際上您處在正確的軌道上,但是您在嘗試解析所有內容而不是僅流傳輸文件並決定在何處剪切時糾結了自己。

根據您的數據,您想剪切以開頭的行(表示作者),並且希望從第一個逗號開始剪切該行。 大概您也想刪除空行。 因此,一個簡單的流修飾符將類似於:

# open quotes_source.txt for reading and quotes_processed.txt for writing
with open("quotes_source.txt", "r", encoding="utf-8") as f_in,\
        open("quotes_processed.txt", "w", encoding="utf-8") as f_out:
    for line in f_in:  # read the input file line by line
        line = line.strip()  # clear out all whitespace, including the new line
        if not line:  # ignore blank lines
            continue
        if line[0] == "—":  # we found the dash!
            # write space, everything up to the first comma and a new line in the end
            f_out.write(" " + line.split(",", 1)[0] + "\n")
        else:
            f_out.write(line)  # a quote line, write it immediately

這就是全部。 只要數據中沒有其他新行,它就會准確地產生您想要的結果,即對於quotes_source.txt文件,其中包含:

“The road to hell is paved with works-in-progress.”
—Philip Roth, WD some other stuff here

“The only thing necessary for the triumph of evil is for good men to do nothing.”
—Edmund Burke, whatever there is

“You know nothing John Snow.”
—The wildling Ygritte, "A Dance With Dragons" - George R.R. Martin

它將產生一個quotes_processed.txt文件,其中包含:

“The road to hell is paved with works-in-progress.” —Philip Roth
“The only thing necessary for the triumph of evil is for good men to do nothing.” —Edmund Burke
“You know nothing John Snow.” —The wildling Ygritte

暫無
暫無

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

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