第一章:文本-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 […]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值