23

使用 Python 的 textwrap 库时,我该如何转:

short line,

long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

进入这个:

short line,

long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxx

我试过:

w = textwrap.TextWrapper(width=90,break_long_words=False)
body = '\n'.join(w.wrap(body))

但我得到:

short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

(在我的例子中间距不准确)

4

8 回答 8

28

尝试

w = textwrap.TextWrapper(width=90,break_long_words=False,replace_whitespace=False)

这似乎为我解决了问题

我从我在这里读到的内容中解决了这个问题(我以前从未使用过 textwrap )

于 2009-07-22T16:05:14.593 回答
17
body = '\n'.join(['\n'.join(textwrap.wrap(line, 90,
                 break_long_words=False, replace_whitespace=False))
                 for line in body.splitlines() if line.strip() != ''])
于 2014-10-23T21:51:52.077 回答
5

如何只换行超过 90 个字符?

new_body = ""
lines = body.split("\n")

for line in lines:
    if len(line) > 90:
        w = textwrap.TextWrapper(width=90, break_long_words=False)
        line = '\n'.join(w.wrap(line))

    new_body += line + "\n"
于 2009-07-22T16:08:01.203 回答
3

TextWrapper 并非旨在处理其中已经包含换行符的文本。

当您的文档已经有换行符时,您可能需要做两件事:

1) 保留旧的换行符,并且只换行超过限制的行。

您可以将 TextWrapper 子类化如下:

class DocumentWrapper(textwrap.TextWrapper):

    def wrap(self, text):
        split_text = text.split('\n')
        lines = [line for para in split_text for line in textwrap.TextWrapper.wrap(self, para)]
        return lines

然后以与 textwrap 相同的方式使用它:

d = DocumentWrapper(width=90)
wrapped_str = d.fill(original_str)

给你:

short line,
long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx

2)删除旧换行符并包装所有内容。

original_str.replace('\n', '')
wrapped_str = textwrap.fill(original_str, width=90)

给你

short line,  long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

(TextWrapper 不执行上述任何一项 - 它只是忽略现有的换行符,这会导致格式奇怪的结果)

于 2017-07-24T18:25:52.377 回答
1

它似乎不支持它。这段代码将扩展它来做我需要的事情:

http://code.activestate.com/recipes/358228/

于 2009-07-22T16:09:25.197 回答
1
lines = text.split("\n")
lists = (textwrap.TextWrapper(width=90,break_long_words=False).wrap(line) for line in lines)
body  = "\n".join("\n".join(list) for list in lists)
于 2009-07-22T16:09:41.670 回答
1

这是一个小模块,可以换行、换行、处理额外的缩进(例如项目符号列表),以及用 markdown 替换字符/单词!

class TextWrap_Test:
    def __init__(self):
        self.Replace={'Sphagnum':'$Sphagnum$','Equisetum':'$Equisetum$','Carex':'$Carex$',
                      'Salix':'$Salix$','Eriophorum':'$Eriophorum$'}
    def Wrap(self,Text_to_fromat,Width):
        Text = []
        for line in Text_to_fromat.splitlines():
            if line[0]=='-':
                wrapped_line = textwrap.fill(line,Width,subsequent_indent='  ')
            if line[0]=='*':
                wrapped_line = textwrap.fill(line,Width,initial_indent='  ',subsequent_indent='    ')
            Text.append(wrapped_line)
        Text = '\n\n'.join(text for text in Text)

        for rep in self.Replace:
            Text = Text.replace(rep,self.Replace[rep])
        return(Text)


Par1 = "- Fish Island is a low center polygonal peatland on the transition"+\
" between the Mackenzie River Delta and the Tuktoyaktuk Coastal Plain.\n* It"+\
" is underlain by continuous permafrost, peat deposits exceede the annual"+\
" thaw depth.\n* Sphagnum dominates the polygon centers with a caonpy of Equisetum and sparse"+\
" Carex.  Dwarf Salix grows allong the polygon rims.  Eriophorum and carex fill collapsed ice wedges."
TW=TextWrap_Test()
print(TW.Wrap(Par1,Text_W))

将输出:

  • 鱼岛是麦肯齐河三角洲和图克托亚克图克沿海平原之间过渡的低中心多边形泥炭地。

    • 它的下面是连续的永久冻土,泥炭沉积物超过了年融化深度。

    • $Sphagnum$ 以 $Equisetum$ 和稀疏的 $Carex$ 为主导的多边形中心。矮小的 $Salix$ 沿着多边形边缘生长。$Eriophorum$ 和 carex 填充塌陷的冰块。

例如,如果您在 matplotlib 中工作,则 $$ 之间的字符将以斜体显​​示,但 $$ 不会计入行间距,因为它们是在之后添加的!

所以如果你这样做了:

fig,ax = plt.subplots(1,1,figsize = (10,7))
ax.text(.05,.9,TW.Wrap(Par1,Text_W),fontsize = 18,verticalalignment='top')

ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)

你会得到: 在此处输入图像描述

于 2018-04-07T18:54:22.913 回答
0

我不得不在格式化动态生成的文档字符串时遇到类似的问题。我想保留手工放置的换行符,并将任何行分割成一定长度。稍微修改@far的答案,这个解决方案对我有用。我只是为了后代把它包括在这里:

import textwrap

wrapArgs = {'width': 90, 'break_long_words': True, 'replace_whitespace': False}
fold = lambda line, wrapArgs: textwrap.fill(line, **wrapArgs)
body = '\n'.join([fold(line, wrapArgs) for line in body.splitlines()])
于 2016-08-24T22:54:57.690 回答