Python textwrap库-如何保留换行符?
在使用Python的textwrap库时,我如何能够将其转换为:Python textwrap库-如何保留换行符?,python,newline,word-wrap,Python,Newline,Word Wrap,在使用Python的textwrap库时,我如何能够将其转换为: short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 为此: short line, long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxx 我试过: w =
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)
这似乎解决了我的问题
我从我读到的内容(我以前从未使用过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"
看起来它不支持这一点。这段代码将对其进行扩展,以满足我的需要:
格式化动态生成的docstring时,我遇到了类似的问题。我想保留手动放置的新行,并将任何行拆分成一定长度。对答案稍加修改,这个解决方案对我有效。我在此仅为子孙后代提供:
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)保留旧换行符,只换行长度超过限制的换行符。
original_str.replace('\n', '')
wrapped_str = textwrap.fill(original_str, width=90)
您可以按如下方式将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不做这两件事——它只是忽略现有的换行符,这会导致格式怪异的结果)这里有一个小模块,它可以包装文本、断行、处理额外的缩进(例如项目符号列表),并用标记替换字符/单词
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$以 木贼$caonpy和苔草$CANOPY。矮人柳$ 沿着多边形边缘生长$枇杷 苔草填充坍塌的冰楔
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)
你会得到:
请注意,在这种情况下,包装器将\n视为字符而不是换行符,例如,它将假定先前发布的是一个单词。在许多情况下,这会导致格式问题。因此,由用户“far”提供的带有“\n”.join()的解决方案更好。感谢您中的一些人帮助我解决我的问题!
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)