有没有办法在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 :(得分: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.
>>>
答案 1 :(得分:0)
看到你的代码后,我不确定还有其他方法可以在每个第n个标记处插入一个新行
但谁知道n应该多大......
你应该把它留给打开文件的程序吗?