【问题标题】:Python textwrap Library - How to Preserve Line Breaks?Python textwrap 库 - 如何保留换行符?
【发布时间】:2010-11-13 01:43:45
【问题描述】:

当使用 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

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

【问题讨论】:

    标签: python newline word-wrap


    【解决方案1】:

    试试

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

    这似乎解决了我的问题

    我从阅读 here 的内容中得出了这一点(我以前从未使用过 textwrap)

    【讨论】:

    • 请注意,在这种情况下,包装器将 \n 视为字符而不是换行符,例如,它将假定previous\npublished 是一个单词。这在许多情况下会导致格式问题。所以用户“far”给出的带有“\n”.join()的解决方案更好。
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:
        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)
        

        【讨论】:

          【解决方案5】:
          body = '\n'.join(['\n'.join(textwrap.wrap(line, 90,
                           break_long_words=False, replace_whitespace=False))
                           for line in body.splitlines() if line.strip() != ''])
          

          【讨论】:

            【解决方案6】:

            我不得不在格式化动态生成的文档字符串时遇到类似的问题。我想保留手动放置的换行符并将任何行拆分为一定长度。通过@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()])
            

            【讨论】:

              【解决方案7】:

              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 不执行上述任何一项 - 它只是忽略现有的换行符,这会导致格式奇怪的结果)

              【讨论】:

                【解决方案8】:

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

                将输出:

                • 鱼岛是一个低中心多边形泥炭地 麦肯齐河三角洲和 Tuktoyaktuk 沿海平原。

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

                  • $Sphagnum$ 以 $Equisetum$ 和稀疏 $Carex$ 的草丛。矮人$Salix$ 沿着多边形边缘生长。 $Eriophorum$ 和 苔藓填充塌陷的冰楔。

                例如,如果您在 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)
                

                你会得到:

                【讨论】:

                • 感谢你们的一部分帮助我解决我的问题!
                猜你喜欢
                • 2013-05-11
                • 1970-01-01
                • 2013-07-08
                • 1970-01-01
                • 1970-01-01
                • 2010-11-03
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多