2016-04-23 82 views
0

有沒有辦法在python3中向文本文件寫入一長串文字,以便可以將字符串寫入多行?這是我到目前爲止所嘗試的。如何將一長串文字寫入文本文件?

這裏就是我試圖做

from nltk.tokenize import word_tokenize 

    my_list = word_tokenize(my_text) 
    my_list_string = ' '.join(my_list) 

    outfile = open("my_comp.txt", "a") 
    outfile.write(my_list_string) 
    outfile.close() 
+0

你的title卻沒有真正符合你的描述 – karina

+0

我認爲這就是你要找的東西http://stackoverflow.com/questions/10660435/pythonic-way-to-create-a-long-multi-line-string – karina

+0

你是什麼意思「字符串可以寫成多行」? – EbraHim

回答

0

看到你的代碼後,我不知道有任何其他方式然後插入一個新行每n個令牌

但誰知道如何大n應該是...

你應該把它留給打開文件的程序?

+0

程序只是打開文件並將其寫入一個「非常長」的行。即使當字符串中有大約1000字時。 –

+0

是的。我明白。這就是你的編輯處理它的方式。如果你在一個支持換行的編輯器中打開它 – karina

+0

否則我可能會遍歷這些標記並在每一行添加一個新行......我不知道......第20個標記? – karina

1

有該庫在Python命名textwrap

>>> import textwrap 
>>> strs = "Is there a way to write a long string of words to a text file in python3 so that the string can be written over several lines? This is what I have tried so far. Is there a way to write a long string of words to a text file in python3 so that the string can be written over several lines? This is what I have tried so far. " 

作如下處理:

>>> print (textwrap.fill(strs, 20)) 
Is there a way to 
write a long string 
of words to a text 
file in python3 so 
that the string can 
be written over 
several lines? This 
is what I have tried 
so far. Is there a 
way to write a long 
string of words to a 
text file in python3 
so that the string 
can be written over 
several lines? This 
is what I have tried 
so far. 

或改變線路長度:

>>> print (textwrap.fill(strs, 40)) 
Is there a way to write a long string of 
words to a text file in python3 so that 
the string can be written over several 
lines? This is what I have tried so far. 
Is there a way to write a long string of 
words to a text file in python3 so that 
the string can be written over several 
lines? This is what I have tried so far. 
>>> 
+0

謝謝!這完美的作品!對於一串數字是否有類似的命令?即使將數字轉換爲字符串後,它似乎也不起作用。 –