python textwrap.md

textwrap

textwrap模块可以用来格式化文本, 使其在某些场合输出更美观. 他提供了一些类似于在很多文本编辑器中都有的段落包装或填充特性的程序功能.

Example Data

本节中的示例使用模块textwrap_example.py,它包含一个字符串sample_text。

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.
    '''

Filling Paragraphs

textwrap.fill(text, width=70, **kwargs):将单个段落包含在文本中,并返回包含包装段落的单个字符串。fill()是下面语句的简写形式" ".join(wrap(text, ...))特别地,fill()接受与wrap()完全相同的关键字参数。

举例
fill()将文本作为输入, 格式化文本作为输出. 让我们看下面是如何对样本文本进行格式化的.

import textwrap
from textwrap_example import sample_text

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

结果是不太理想的。文本现在是对的,但是第一行保留了它的缩进,并且每个后续行前面的空格都嵌入到段落中。
输出:

     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.

Removing Existing Indentation

textwrap.dedent(text):从文本中的每一行中删除任何常见的前导空格。这可以用于使三引号字符串与显示器的左边缘对齐,同时仍以缩进形式在源代码中呈现它们。注意,制表符和空格都被视为空格,但它们不相等:“ hello”和" hello"被视为没有共同的前导空格。

举例
前面的示例中包含了嵌入的选项卡和额外的空格,因此它的格式不太整齐。使用dedent()从示例文本中的所有行中删除公共空白前缀可以产生更好的输出结果,并允许直接从Python代码中使用docstrings或嵌入式多行字符串,同时删除代码本身的格式。示例字符串有一个人为的缩进级别,用于演示该特性。

import textwrap
from textwrap_example import sample_text

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

输出:

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”的相反, 结果就是将每行开始的普通空白符删除了. 如果某行已经比另一行多了个缩进层次, 那么对应的空格不会被去掉.

import textwrap
abc = """
 Line one.
   Line two.
 Line three.
"""

print(textwrap.dedent(abc))

输出:

Line one.
  Line two.
Line three.

Combining Dedent and Fill

接下来, 让我们看下如果我们传递非缩进格式的文本给fill(), 并使用一些不同的宽度值, 会发生什么.

import textwrap
from textwrap_example import sample_text

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

使用不同行宽值进行格式化输出:

 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.

Indenting Blocks

textwrap.indent(text, prefix, predicate=None):将前缀添加到文本中选定行的开头。行通过调用text.splitlines(True)分隔。默认情况下,前缀添加到不仅包含空格(包括任何行结尾)的所有行。

举例
使用indent()函数为字符串中的所有行添加一致的前缀文本。这个示例将相同的示例文本格式化,就好像它是在应答中引用的电子邮件消息的一部分,使用它作为每一行的前缀。

import textwrap
from textwrap_example import sample_text

dedented_text = textwrap.dedent(sample_text)
wrapped = textwrap.fill(dedented_text, width=50)
wrapped += '

Second paragraph after a blank line.'
final = textwrap.indent(wrapped, '>')

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

文本块在换行符上被分割,前缀被添加到包含文本的每一行中,然后将这些行合并回一个新字符串并返回。输出:

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.

要控制哪些行接收新前缀,请将可调用的predicate 参数传递给indent()。可调用的每一行文本将被调用,并为返回值为true的行添加前缀。

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('
Quoted block:
')
print(final)

此示例将前缀EVEN添加到包含偶数个字符的行。

Indent ' The textwrap module can be used to format text
'?
Indent 'for output in situations where pretty-printing is
'?
Indent 'desired.  It offers programmatic functionality
'?
Indent 'similar to the paragraph wrapping or filling
'?
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.

Hanging Indents

举例
就像可以设置输出的宽度一样,第一行的缩进可以独立于后续行控制。

import textwrap
from textwrap_example import sample_text

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

这样就可以产生一个挂起的缩进,其中第一行的缩进比其他行要少。

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.

缩进的值也可以包括非空格字符。例如,悬挂的缩进可以被预先设定,以产生弹点。

Truncating Long Text

textwrap.shorten(text, width, **kwargs):折叠并截断给定的文本以适合给定的宽度。首先,文本中的空格将折叠(所有空格都由单个空格替换)。如果结果符合width,则返回。否则,从尾部删除足够的单词,以使剩余单词加上placeholder适合width。

举例
要截断文本以创建摘要或预览,使用shorten()。所有现有的空白,如制表符、换行符和多个空间的序列,都将被标准化到一个单独的空间。然后,文本将被截断为小于或等于请求的长度,在单词边界之间,这样就不会包含部分单词。

import textwrap
from textwrap_example import sample_text

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

print('Original:
')
print(original)

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

print('
Shortened:
')
print(shortened_wrapped)

如果非空白文本作为截断的一部分从原始文本中删除,则将替换为占位符值。 可以通过为shorten()供一个占位符参数来替换默认值[...]。

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 [...]
原文地址:https://www.cnblogs.com/cuchadanfan/p/7152015.html