第一章:文本-textwrap:格式化文本段落-截断长文本

1.2.7 截断长文本
可以使用shorten()截断长文本来创建一个小结或预览。所有现有的空白符(如制表符、换行符以及多个空格组成的序列)都会被规范化为一个空格。然后文本将被截断为小于或等于指定的长度,而且会在单词边界之间截断,避免包含不完整的单词。

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来替代默认值[…]

运行结果:

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 un many text editors.

Shortened:

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

猜你喜欢

转载自blog.csdn.net/weixin_43193719/article/details/86654705