1.2 textwrap-格式化文本段落
目的 通过调整段落中的换行位置,对文本进行格式化。
textwrap模块可以用来在需要漂亮的打印时对文本进行格式化输出。它提供的编程功能类似于许多文本编辑器和文字处理程序中的段落包装或填充功能。
1.2.1 示例数据
本节中的例子使用了textwrap_example.py模块,其中包含一个字符串sample_text
sample_text = '''
textwrap模块可用于在需要漂亮打印的情况下对文本进行格式 化输出。它提供类似于许多文本编辑器中的段落包装或填充功能的程序化功能。
'''
1.2.2 填充段落
fill()函数将文本作为输入,并产生格式化的文本作为输出。
import textwrap
from textwrap_example import sample_text
print ’No dedent:\n’
print textwrap.fill(sample_text, width=50)
其结果是不太理想的。现在的文本是左对齐的,但第一行保留了缩进,后面每一行的空格都嵌入到段落中。
No dedent:
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.
1.2.3移除现有缩进
前面的示例在输出中混合了制表符和额外的空格,所以它的格式化不是很干净。从样本文本的所有行中去除常见的空白序号会产生更好的结果,并允许直接从Python代码中使用文档字符串或嵌入式多行字符串,同时删除代码格式本身。示例字符串有一个特殊的缩进级别,用于说明此功能。
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”的反义词,其结果是一个文本块,每行共同的初始空白被删除。如果一行已经比另一行缩进得多,一些空白将不会被删除。
输入如:
Line one.
Line two.
Line three.
成为:
Line one.
Line two.
Line three.
1.2.4 结合Dedent和Fill
接下来,可以通过fill()函数,用一些不同的宽度来传递被扣除的文本
接下来,可以通过fill()函数,传递具有不同的width values.
import textwrap
from textwrap_example import sample_text
dedented_text = textwrap.dedent(sample_text).strip()
for width in [ 45, 70 ]:
print ’%d Columns:\n’ % 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.
70 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.
1.2.5 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.
缩进值也可以包含非空白字符。悬挂缩进可以加上前缀*以产生项目符号等。