簡體   English   中英

如何將輸出保存到python中的文件中?

[英]How to save the output into a file in python?

我的代碼如下:

handle = open('abc.txt','r')
tokens = []
sys.stdout=open("test.txt","w")
for line in handle:
    tokens+=word_tokenize(line)
print(tokens)
sys.stdout.close()

當我嘗試運行它時,它在我的計算機上需要很長時間(超過 40 分鍾),但如果不保存在文件中只需要幾秒鍾。 可以通過什么方式更改代碼,以便在最短的時間內將輸出寫入文件?

你正在尋找這樣的東西:

from itertools import chain
with open('abc.txt') as infile:
    tokens = list(chain(*map(word_tokenize, infile)))
with open("test.txt","w") as outfile:
    outfile.write("\n".join(tokens))

您的令牌將每行保存一個令牌。

暫無
暫無

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

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