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()是下面语句的简写形式"\n".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”和"\thello"被视为没有共同的前导空格。

举例
前面的示例中包含了嵌入的选项卡和额外的空格,因此它的格式不太整齐。使用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:\n'.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 += '\n\nSecond paragraph after a blank line.'
final = textwrap.indent(wrapped, '>') print('Quoted block:\n')
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('\nQuoted block:\n')
print(final)

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

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.

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:\n')
print(original) shortened = textwrap.shorten(original, 100)
shortened_wrapped = textwrap.fill(shortened, width=50) print('\nShortened:\n')
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 [...]

python textwrap.md的更多相关文章

  1. python textwrap的使用

    参考:https://docs.python.org/3.6/library/textwrap.html textwrap模块提供了一些方便的函数,以及TextWrapper类,它执行所有的工作.如果 ...

  2. Python sys.md

    sys-System-specific Configuration Interpreter Settings sys包含用于访问解释器的编译时或运行时配置设置的属性和函数. Build-time Ve ...

  3. Python csv.md

    csv csv模块可以用于处理从电子表格和数据库导出的数据到带有字段和记录格式的文本文件,通常称为逗号分隔值(csv)格式,因为逗号通常用于分隔记录中的字段. Reading csv.reader(c ...

  4. Python time.md

    time模块 Comparing Clocks time.clock():在Unix 上,返回当前的处理器时间,以浮点数秒数表示. time.monotonic():返回一个单调时钟的值(在分秒内), ...

  5. python 实现 md文档自动编号

    目录 1. 原理 2. 运行方法 3. 效果 4. 代码 1. 原理 正则匹配对相应字符串进行替换 2. 运行方法 python md_convert.py [a.md, b.md,...] # 转换 ...

  6. Python textwrap模块(文本包装和填充)

    textwrap提供函数wrap().fill().indent().dedent()和以及TextWrapper类. 通常包装或者填充一两个字符串使用wrap()和fill().其他情况使用Text ...

  7. Python os.md

    os 便携式访问操作系统的特定功能.os模块提供了对特定平台模块(如posix, nt, mac)的封装, 函数提供的api在很多平台上都可以相同使用, 所以使用os模块会变得很方便. 但不是所有函数 ...

  8. python string.md

    string 包含用于处理文本的常量和类.string模块始于Python的最早版本. 2.0版本中, 许多之前只在模块中实现的函数被转移为string对象的方法. 之后的版本中, 虽然这些函数仍然可 ...

  9. Python glob.md

    glob 即使glob API非常简单, 但这个模块包含了很多的功能. 在很多情况下, 尤其是你的程序需要寻找出文件系统中, 文件名匹配特定模式的文件时, 是非常有用的. 如果你需要包含一个特定扩展名 ...

随机推荐

  1. vs2017调试浏览器闪退

    工具>选项>项目和解决方案> Web项目",取消选中"浏览器窗口关闭时停止调试器"

  2. SQL 查询结果加序列号

    SQL ROW_NUMBER() OVER(ORDER BY ID) Oracle rownum

  3. [android] 轮播图-无限循环

    实现无限循环 在getCount()方法中,返回一个很大的值,Integer.MAX_VALUE 在instantiateItem()方法中,获取当前View的索引时,进行取于操作,传递进来的int ...

  4. CentOS7 mini安装后没有ifconfig命令的解决办法

    在CentOS 最小化mini安装后,没有ifconfig命令,此时网卡也没有启动,所以无法yum安装net-tools. 下面三步解决此问题: 1 查看网卡名称 ip addr 2 启动网卡 ifu ...

  5. 【转载】Nginx+Tomcat 动静分离实现负载均衡

    0.前期准备 使用Debian环境.安装Nginx(默认安装),一个web项目,安装tomcat(默认安装)等. 1.一份Nginx.conf配置文件 1 # 定义Nginx运行的用户 和 用户组 如 ...

  6. 【Linux】CentOS安装solr 4.10.3

    Solr是什么? Solr 是Apache下的一个顶级开源项目,采用Java开发,它是基于Lucene的全文搜索服务器.Solr提供了比Lucene更为丰富的查询语言,同时实现了可配置.可扩展,并对索 ...

  7. 盒子模型的margin负数用法

    盒子的margin用法大家都应该很清楚,在实际中一般使用margin来水平居中或者让自己移动相应的位置,但是margin给负数在实际中也是有用的. 如图为两个浮动的盒子. 给左边的盒子margin-l ...

  8. Vue:v-on自定义事件

    Vue中父组件使用prop向子组件传递数据,那么子组件向父组件使用什么方式传递信息:自定义事件. 1.先来看官网上面教程 每个 Vue 实例都实现了事件接口,即: 使用 $on(eventName)  ...

  9. 数据操作语句(DML)

    增加(插入)数据 SQL>insert into 表名 values(值1,值2 /*根据表中的字段顺序和字段类型相应填写*/); SQL>commit; (提交,提交了别的人才看看到这个 ...

  10. Three.js开发指南---使用高级几何体和二元操作(第六章)

    本章的主要内容: 一,高级几何体-凸面体ConvexGeometry,扫描体LatheGeometry,管状几何体TubeGeometry: 二,使用拉伸几何体ExtrudeGeometry将一个二维 ...