Python textwrap库 - 如何保留换行符?
问题描述:
当使用Python的textwrap库,我怎样才能把这个: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
(间距不准确的在我的例子)
答
尝试
w = textwrap.TextWrapper(width=90,break_long_words=False,replace_whitespace=False)
,似乎解决这个问题对我来说
我的工作了这一点从我读here(我从来没有用过textwrap前)
答
如何只换行超过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"
答
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)
答
body = '\n'.join(['\n'.join(textwrap.wrap(line, 90,
break_long_words=False, replace_whitespace=False))
for line in body.splitlines() if line.strip() != ''])
答
我有一个类似的问题格式化动态生成的文档字符串。我想保留用手放置的换行符和将任何行分割一定的长度。稍微修改答案@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()])
答
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没有做任何的这些 - 它只是忽略了现有的换行,这会导致一个古怪的格式的结果)
要注意的是在这种情况下,包装器将\ n视为字符而不是断行器,例如它会假定先前\ n已发布的是一个字。这在很多情况下会导致格式问题。因此,用户“far”给出的带有“\ n”.join()的解决方案更好。 – Zulko 2015-02-21 10:33:05