簡體   English   中英

從txt讀取時,如何綁定行尾和行首?

[英]How to bond end of row and start of line while reading from txt?

我有一個這樣的txt,我是從txt文件中讀取的。

that's mai purpose! in order not to.
go and.. ll' be in h'van,. 

我想創建一個這樣的列表: ["that's","mai","purpose!","in","order","not","to.\\ngo","and..","ll'","be","in","h'van,."]

我嘗試了split()但是直到\\n部分我該如何處理? 困難的部分是“ to.\\ngo ”,謝謝!

您需要調用file.read()以將所有內容作為單個字符串獲取,然后調用str.split將單詞拆分為:

with open('/path/to/file.txt') as f:
    my_file_str = f.read()
    my_list = my_file_str.split(' ')
    #         split on space ' ' ^

嘗試這個:

with open("c.txt") as f:
     lines = f.read()
     mlist = lines.strip().split(' ')
print mlist

輸出:

["that's", 'mai', 'purpose!', 'in', 'order', 'not', 'to.\ngo', 'and..', "ll'", 'be', 'in', "h'van,."]

暫無
暫無

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

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