如何在python中使用textwrapper进行文件操作

2024-06-07 10:54:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图写一个输出文件,限制每行字符60个字符。我设法读入文本文件,使它每行60个字符,但是它添加了不应该在同一行的单词。例如,读入文件是

Albuquerque is my turkey and he's feathered and he's fine, And he
wobbles and he gobbles and he's
absolutely mine

He's the best pet you can get yet better than
a dog or cat, He's my albuquerque turkey and i'm awfully proud of that

使用文本包装方法之后

Albuquerque is my turkey and he's feathered and he's fine,
And he wobbles and he gobbles and he's absolutely mine  He's

the best pet you can get yet better than a dog or cat, He's
my albuquerque turkey and i'm awfully proud of that

应该是的

Albuquerque is my turkey and he’s feathered and he’s fine,
And he wobbles and he gobbles and he’s absolutely mine

He’s the best pet you can get yet, better than a dog or cat,
He’s my albuquerque turkey and i’m awfully proud of that

如何调整文本包装方法以适应句子

def adjust_linelength():
    with open("essay_neb.txt") as file:
        text = file.read().strip()
    with open("essay_final.txt", 'w') as file:
        file.write(textwrap.fill(text, width=60))

Tags: andismyfileheminefineturkey
1条回答
网友
1楼 · 发布于 2024-06-07 10:54:32

根据textwrap documentation for 2.7

textwrap.fill(text[, width[, ...]])

Wraps the single paragraph in text, and returns a single string containing the wrapped paragraph.

如果你先把文本分成段落,然后在每个段落上运行textwrapper,它应该可以工作

相关问题 更多 >

    热门问题