我想使用python和textwrap模块读取文本文件。文本文件没有结构化,我想将其结构化为70个标记,每个段落每行5行
我尝试使用textwrap模块来执行此操作,但是它总是抛出如下错误消息:AttributeError:'list'对象没有属性'expandtabs'
第一次尝试:
with open("python.txt", "r", encoding="utf-8") as f:
paragraphs = f.read().split("\n\n")
textwrap.wrap (paragraphs, width=70)
print (paragraphs)
第二次尝试:
with open("python.txt", "r", encoding="utf-8") as f:
paragraphs = f.read().split("\n\n")
#textwrap.wrap (paragraphs, width=70)
#print(*textwrap.fill (paragraphs, width=70))
width = 70
class TextWrapper(width):
pass
paragraphs = textwrap.TextWrapper(width=70)
paragraphs, (len(paragraphs) + lines - 1) / lines# can be used to have an evenly number of lines
print (paragraphs)
输出应看起来像文本,每行的宽度为70 每个段落有5行
答案 0 :(得分:1)
您应该以文本形式而不是列表形式传递文本:
with open("python.txt", "r", encoding="utf-8") as f:
formatted = textwrap.wrap(f.read(), width=70)