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. iphone safari浏览器CSS兼容性的解决方案集合

    1.iphone safari不兼容CSS的active的解决方案如下: <body ontouchstart="" onmouseover=""> ...

  2. Java虚拟机--线程安全和锁优化

    Java虚拟机--线程安全和锁优化 线程安全 线程安全:当多线程访问一个对象时,如果不用考虑这些线程在运行时环境下的调度和交替执行,也不需要额外的同步,或者在调用方进行任何其他的协调操作,调用这个对象 ...

  3. Lucene 学习-安装 Elasticsearch 服务器

    全文搜索属于最常见的需求,开源的 Elasticsearch 是目前全文搜索引擎的首选,它的底层是开源库 Lucene.但是我们没法直接使用 Lucene,必须自己写代码去调用它的接口. Elasti ...

  4. 还是畅通工程(hdu1233)并查集应用

    还是畅通工程 Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Sub ...

  5. Android-Handler使用姿势

    http://www.jianshu.com/p/8e9a54f1826e 好文章先马,慢慢看

  6. 漫画 | Java多线程与并发(二)

    1.什么是线程池? 为什么要使用它? 2.Java中invokeAndWait 和 invokeLater有什么区别? 3.多线程中的忙循环是什么? 4.Java内存模型是什么? 线程内的代码能够按先 ...

  7. Java JDBC SqlServer

    一.驱动 下载地址:https://www.microsoft.com/en-us/download/details.aspx?id=11774 引用Jar包时注意区分Java版本: Sqljdbc4 ...

  8. 【VS2015】Win7 X64上面安装VS2015

    环境: 1.Win7 x64 SP1旗舰版 2.VS2015专业版Update3 3.IE11 4.WDK10 5.SDK10   安装步骤: 1.安装IE11,需要如下补丁:     a.Windo ...

  9. 《Spring实战》-- 'cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element' 错误的解决办法

    在Eclipse中新建了一个maven项目学习Spring,在 service.xml 中配置 Spring,想要学习'面向切面的Spring',service.xml 内容如下: <beans ...

  10. MonkeyRunner进坑——errors importing other modules

    后知后觉,刚知道Android提供了MonkeyRunner这么个东西,能用来干嘛呢,官方文档介绍得很清楚.简单说,可以用Python程序通过API, installs an Android appl ...