Python textwrap Library - How to Preserve Line Breaks?

后端 未结 8 933
礼貌的吻别
礼貌的吻别 2021-02-04 02:19

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

short line,

long line xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
         


        
8条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-04 02:54

    Here is a little module that can wrap text, break lines, handle extra indents (eg.a bulleted list), and replace characters/words with 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.

    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!

    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:

提交回复
热议问题