Python Module之textwrap - 文本段落格式编排

模块目的:通过调整每行文本的断句位置来对段落文本进行格式化编排。

在一些需要文本美观输出(打印)的场景中,textwrap模块可以用来格式化编排文本。它提供了类似于在许多文本编辑器和文字处理器中使用的段落包装、填充等程序化功能。


样例数据

本节的样例我们建立textwrap_example.py模块,其包含一个多行字符串sample_text

# textwrap_example.py
sample_text = '''
    The textwrap module can be used to format text for output in
    situations where pretty-printing is desired.  It offers
    programmatic functionality similar to the paragraph wrapping
    or filling features found in many text editors.
    '''

填充段落(Fill)

fill()方法使用文本作为输入,并返回格式化之后的文本。

# textwrap_fill.py

import textwrap
from textwrap_example import sample_text

print(textwrap.fill(sample_text, width=50))

结果并不令人满意。文本现在被左对齐,但是第一行文本保留了其行首缩进,而其余各行行首的空白都被嵌入到了段落中间。

$ python3 textwrap_fill.py

     The textwrap module can be used to format
text for output in     situations where pretty-
printing is desired.  It offers     programmatic
functionality similar to the paragraph wrapping
or filling features found in many text editors.

去除“空白”(Dedent)

在上个例子中,我们的格式化文本输出中间混杂着一些制表符和多余的空白,所以它看起来并不美观。dedent()方法可以去除样例字符串中每一行文本行首的共有空白,这样可以使结果看起来更美观。样例字符串是为了说明该特性人为的加上的空白。

# textwrap_dedent.py

import textwrap
from textwrap_example import sample_text

dedented_text = textwrap.dedent(sample_text)
print('Dedented:')
print(dedented_text)

结果开始变得美观起来:

$ python3 textwrap_dedent.py

Dedented:

The textwrap module can be used to format text for output in
situations where pretty-printing is desired.  It offers
programmatic functionality similar to the paragraph wrapping
or filling features found in many text editors.

dedent()(去除缩进)是”indent”(缩进/空白)的对立面,dedent()方法的结果就是每一行文本行首的共有空白被去除了。但是如果有一行文本本身比其他行多一些空白,那么这些多出来的空白将不会被去除。

比如,我们用下划线_代替空白,输入:

_Line one.
__Line two.
_Line Three.

那么输出结果是:

Line one.
_Line two.
Line Three.

Dedent和Fill结合使用

接下来,去除行首空白之后的文本可以传递给fill()方法,并使用不同的width参数值来测试:

# textwrap_fill_width.py

import textwrap
from textwrap_example import sample_text

dedented_text = textwrap.dedent(sample_text).strip()
for width in [45, 60]:
    print('{} Columns: \n'.format(width))
    print(textwrap.fill(dedented_text, width=width))
    print()

结果如下:

$ python3 textwrap_fill_width.py

45 Columns:

The textwrap module can be used to format
text for output in situations where pretty-
printing is desired.  It offers programmatic
functionality similar to the paragraph
wrapping or filling features found in many
text editors.

60 Columns:

The textwrap module can be used to format text for output in
situations where pretty-printing is desired.  It offers
programmatic functionality similar to the paragraph wrapping
or filling features found in many text editors.

添加缩进文本

使用indent()方法可以在一个多行字符串的每一行行首添加一致的前缀文本。下述例子在一个样例字符串的每一行行首添加>前缀,使其变成邮件回复中被引用的格式。

# textwrap_indent.py

import textwrap
from textwrap_example import sample_text

dedented_text = textwrap.dedent(sample_text)
wrapped = textwrap.fill(dedented_text, width=50)
wrapped += '\n\nSecond paragraph after a blank line.'
final = textwrap.indent(wrapped, '> ')

print('Quoted block:\n')
print(final)

样例段落被分割成新的每一行,并在每一行前面加上前缀>,接着这些行组成一个新的字符串并返回。

$ python3 textwrap_indent.py

Quoted block:

>  The textwrap module can be used to format text
> for output in situations where pretty-printing is
> desired.  It offers programmatic functionality
> similar to the paragraph wrapping or filling
> features found in many text editors.

> Second paragraph after a blank line.

如果我们想要控制给哪些行添加前缀,可以给indent()方法传递predicate断言参数,该参数是一个方法,对每一行文本,indent()方法先调用该方法进行判断,如果该方法返回True,则在这一行前面添加前缀,否则不添加。

# textwrap_indent_predicate.py

import textwrap
from textwrap_example import sample_text

def should_indent(line):
    print('Indent {!r}?'.format(line))
    return len(line.strip()) % 2 == 0

dedented_text = textwrap.dedent(sample_text)
wrapped = textwrap.fill(dedented_text, width=50)
final = textwrap.indent(wrapped, 'EVEN ', predicate=should_indent)

print('\nQuoted block:\n')
print(final)

结果是我们只给长度为偶数的每一行添加了前缀:

$ python3 textwrap_indent_predicate.py

Indent ' The textwrap module can be used to format text\n'?
Indent 'for output in situations where pretty-printing is\n'?
Indent 'desired.  It offers programmatic functionality\n'?
Indent 'similar to the paragraph wrapping or filling\n'?
Indent 'features found in many text editors.'?

Quoted block:

EVEN  The textwrap module can be used to format text
for output in situations where pretty-printing is
EVEN desired.  It offers programmatic functionality
EVEN similar to the paragraph wrapping or filling
EVEN features found in many text editors.

凸排(段落内缩)

我们也可以使用fill()方法实现添加前缀,同样的,我们可以设置输出的宽度,并且第一行文本的前缀文本可以单独设置。

# textwrap_hanging_indent.py

import textwrap
from textwrap_example import sample_text

dedented_text = textwrap.dedent(sample_text)
print(textwrap.fill(dedented_text, initial_indent='', subsequent_indent=' ' * 4, width=50))

这样可以很容易产生一段“凸排”文字,即第一行文本的缩进比其他行少。

$ python3 textwrap_hanging_indent.py

The textwrap module can be used to format text for
    output in situations where pretty-printing is
    desired.  It offers programmatic functionality
    similar to the paragraph wrapping or filling
    features found in many text editors.

前缀文本也可以是非空白字符,比如可以用星号*,这样就可以产生一段条列要点。


截断长字符串

我们可以使用shorten()方法来截断较长的字符串以此来产生一段摘要或概述。所有的空白字符,比如制表符、换行符、成串的空格都会被替换成一个空格。文本会以少于或等于所要求的文本长度而截断,截断的地方都在单词边界以避免不完整单词的出现。

# textwrap_shorten.py

import textwrap
from textwrap_example import sample_text

dedented_text = textwrap.dedent(sample_text)
original = textwrap.fill(dedented_text, width=50)

print('Original:\n')
print(original)

shortened = textwrap.shorten(original, 100)
shortened_wrapped = textwrap.fill(shortened, width=50)

print('\nShortened:\n')
print(shortened_wrapped)

如果原始字符串中的非空白字符被去除,那么它会被一个占位符代替。默认的占位符是[...],它可以通过给shorten()方法传递一个placeholder参数来设置。

$ python3 textwrap_shorten.py

Original:

 The textwrap module can be used to format text
for output in situations where pretty-printing is
desired.  It offers programmatic functionality
similar to the paragraph wrapping or filling
features found in many text editors.

Shortened:

The textwrap module can be used to format text for
output in situations where pretty-printing [...]

原文点这里

参考:
1.textwrap模块的官方文档

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: TextwrapPython 中的一个标准库模块,主要用于格式化输出的文本,使其更美观。这个模块主要提供了两个函数:fill() 和 wrap()。 fill() 函数用于将文本段落按照指定的宽度进行换行,并返回换行后的字符串。它的使用方法如下: ``` import textwrap text = ''' The textwrap module can be used to format text for output in different ways, such as wrapping long lines, and aligning text. It offers several convenient functions to perform these text formatting tasks. ''' print(textwrap.fill(text, width=40)) ``` 上面的代码将文本段落按照 40 个字符的宽度进行换行,然后输出换行后的字符串。 wrap() 函数用于将文本段落按照指定的宽度进行换行,并返回一个包含多个字符串的列表。它的使用方法如下: ``` import textwrap text = ''' The textwrap module can be used to format text for output in different ways, such as wrapping long lines, and aligning text. It offers several convenient functions to perform these text formatting tasks. ''' print(textwrap.wrap(text, width=40)) ``` 上面的代码将文本段落按照 40 个字符的宽度进行换行,然后返回一个包含多个字符串的列表。 除了 fill() 和 wrap() 两个函数之外,Textwrap 还提供了一些其他函数来完成更多的文本格式化任务,例如填充文本、对齐文本、设置前导空格等。更多细节可以参考 Python 官 ### 回答2: TextwrapPython的一个模块,它用于格式文本段落,以便更美观地输出。这个模块提供了一些功能,能够自动调整文本的换行和缩进,使得文本在输出时更加整齐。 Textwrap模块的主要方法是wrap()和fill()函数。wrap()函数接受一个字符串和一个宽度参数,然后返回一个列表,其中的每一个元素都是根据指定宽度自动换行的文本段落。fill()函数则是将字符串包装成一个段落,并根据指定的宽度自动换行。 除了wrap()和fill()函数之外,Textwrap模块还提供了一些其他的方法,如indent()函数用于在文本段落前添加缩进、dedent()函数用于去除文本段落的缩进、和shorten()函数用于缩短长句子等。 使用Textwrap模块可以轻松地实现格式化输出文本。例如,如果你有一个长句子,你可以使用wrap()函数将其分成多行,并指定每行的宽度。或者你可以使用fill()函数将一个段落包装成一行,并指定宽度。此外,你还可以使用indent()函数为文本段落添加缩进,以获得更好的排版效果。 总之,Textwrap模块是一个非常实用的工具,可以帮助我们方便地对文本段落进行格式化处理,使得输出的文本更加美观。无论是在命令行界面还是在网页中,使用Textwrap模块都可以改善文本的显示效果,提升用户的阅读体验。 ### 回答3: TextwrapPython中的一个模块,用来格式文本段落,使其更美观。它提供了一些函数和方法,用于自动调整文本的换行和缩进。 使用Textwrap可以轻松地将文本段落转换为指定的宽度,并自动换行。可以同时设置左侧和右侧的缩进,还可以控制每行的缩进字符。 Textwrap提供了几个常用的函数和方法,比如`wrap()`函数用于将文本按照指定的宽度进行换行,返回一个包含换行后文本的列表;`fill()`函数用于根据指定的宽度将文本进行换行,并返回一个字符串;`shorten()`函数用于缩短文本的长度,将超出指定长度的部分用省略号替代。 除了这些常用的函数和方法,Textwrap还提供了一些用于定制换行行为的选项和参数。比如可以指定换行时是否保留单词完整性,可以指定缩进字符和缩进级别等。这些选项和参数可以根据实际需求进行灵活配置,以得到最符合要求的文本格式化效果。 总而言之,Textwrap是一个功能强大的模块,可以帮助我们将文本段落格式化输出,使其更加美观。它提供了多种函数和方法,可以根据需要进行灵活配置,从而得到满足要求的文本格式化效果。无论是生成报告、打印输出还是网页排版,Textwrap都可以帮助我们轻松实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值