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. JS继承实现的几种方式

    //继承的几种实现: //解决方案1.通过原型继承 function Parent1(){ this.name = 'Parent1'; } function Child1(){} Child1.pr ...

  2. Java基础——6种常用类讲解

    本文主要介绍几种Java中常用类的应用. 一.System类 从API当中我们可以看出,public final class System exends Object.System类包含一些有用的字段 ...

  3. Go 语言相关的优秀框架,库及软件列表

    If you see a package or project here that is no longer maintained or is not a good fit, please submi ...

  4. Mybatis之SessionFactory原理

    Mybatis在使用前需进行初始化,下面就针对Mybatis的初始化过程进行介绍.Mybatis的初始化过程有两种:基于XML和基于Java API两种方式,下面就针对基于XML的方式进行展开. 一. ...

  5. Oracle中UNION和ORDER BY共用方法

    问题 SQL语句中,UNION拼接两个单独的SQL时候,单独的SQL中加入ORDER BY会报错,ORDER BY只能放在句末. // 会报错的语句 SELECT S.S_ID AS ID,S.S_N ...

  6. es6 export与export default 的区别

    相同点: 均可用于导出常量.函数.文件.模块等 不同点: 1.在一个文件中export可以有多个,但export default 只能有一个: export var firstName = 'Mich ...

  7. git 常见命令,规范 整理

    move commit to stage area(把本地的1个commit还原到 暂存区) git reset --soft HEAD~1 把其他的commit的合并到现在到分支:git cherr ...

  8. CentOS7下 将django工程部署到Apache2.4上

    因为需要写一个网站,考虑到也没写过其他的语言,就直接采用了python,说起python的框架,就是大名鼎鼎的Django啦. 工程所采用的版本是python 2.7,django 是1.8,wind ...

  9. singleInstance和singleTask导致startActivityForResult回调失败

    先来了解下这两种启动模式: 1.singleInstance,全局唯一,它的实例在全局(即在众多任务栈中)是唯一的,它单独地存在于属于自己的任务栈中,而且这个任务栈没有其他实例. 2.singleTa ...

  10. Unity Profiler连接Android真机调试

    Profiler在Editor模式就可以观看性能消耗,但是毕竟电脑配置高,跟手机真机环境还是有区别.实际开发中的优化还是推荐用真机测试. 因为IOS一般比Android手机的配置高,在Android平 ...