Python textwrap 库 - 如何保留换行符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1166317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:37:52  来源:igfitidea点击:

Python textwrap Library - How to Preserve Line Breaks?

pythonnewlineword-wrap

提问by Greg

When using Python's textwrap library, how can I turn this:

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

short line,

long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

into this:

进入这个:

short line,

long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxx

I tried:

我试过:

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

But I get:

但我得到:

short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

(spacing not exact in my examples)

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

回答by Peter

try

尝试

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

that seemed to fix the problem for me

这似乎解决了我的问题

I worked that out from what I read here(I've never used textwrap before)

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

回答by far

body = '\n'.join(['\n'.join(textwrap.wrap(line, 90,
                 break_long_words=False, replace_whitespace=False))
                 for line in body.splitlines() if line.strip() != ''])

回答by tefozi

How about wrap only lines longer then 90 characters?

如何只换行超过 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"

回答by Greg

It looks like it doesn't support that. This code will extend it to do what I need though:

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

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

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

回答by John Kugelman

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)

回答by June Skeeter

Here is a little module that can wrap text, break lines, handle extra indents (eg.a bulleted list), and replace characters/words with markdown!

这是一个小模块,可以换行、换行、处理额外的缩进(例如项目符号列表),并用 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))

Will output:

将输出:

  • Fish Island is a low center polygonal peatland on the transition between the Mackenzie River Delta and the Tuktoyaktuk Coastal Plain.

    • It is underlain by continuous permafrost, peat deposits exceede the annual thaw depth.

    • $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.

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

    • 它的下面是连续的多年冻土,泥炭沉积超过了每年的解冻深度。

    • $Sphagnum$ 以 $Equisetum$ 和稀疏 $Carex$ 的簇状支配着多边形中心。矮人 $Salix$ 沿着多边形边缘生长。$Eriophorum$ 和carex 填充倒塌的冰楔。

Characters between the $$ would be in italics if you were working in matplotlib for instance, but the $$ won't count towards the line spacing since they are added after!

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

So if you did:

所以如果你这样做:

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)

You'd get: enter image description here

你会得到: 在此处输入图片说明

回答by Lex Scarisbrick

I had to a similar problem formatting dynamically generated docstrings. I wanted to preserve the newlines put in place by hand andsplit any lines over a certain length. Reworking the answer by @fara bit, this solution worked for me. I only include it here for posterity:

我不得不在格式化动态生成的文档字符串时遇到类似的问题。我想保留手工到位换行符一定长度分割的行。稍微修改@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()])

回答by Peter

TextWrapper is not designed to handle text that already has newlines in it.

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

There are a two things you may want to do when your document already has newlines:

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

1) Keep old newlines, and only wrap lines that are longer than the limit.

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

You can subclass TextWrapper as follows:

您可以将 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

Then use it the same way as textwrap:

然后像 textwrap 一样使用它:

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

Gives you:

给你:

short line,
long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx

2) Remove the old newlines and wrap everything.

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

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

Gives you

给你

short line,  long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

(TextWrapper doesn't do either of these - it just ignores the existing newlines, which leads to a weirdly formatted result)

(TextWrapper 不做任何一个——它只是忽略现有的换行符,这会导致一个奇怪的格式结果)