python3從零學習-5.1.5、文本自動換行與填充模塊textwrap

TextWrapper 模塊提供了一些快捷函數,以及可以完成所有工作的類 TextWrapper

如果你只是要對一兩個文本字符串進行自動換行或填充,快捷函數應該就夠用了;否則的話,你應該使用 TextWrapper 的實例來提高效率。

textwrap.wrap(text, width=70, **kwargs)對 text (字符串) 中的單獨段落自動換行以使每行長度最多為 width 個字符。 返回由輸出行組成的列表,行尾不帶換行符。可選的關鍵字參數對應於 TextWrapper 的實例屬性,具體文檔見下。 width 默認為 70。請參閱 TextWrapper.wrap() 方法瞭解有關 wrap() 行為的詳細信息。def wrap(text, width=70, **kwargs):

"""Wrap a single paragraph of text, returning a list of wrapped lines.

Reformat the single paragraph in 'text' so it fits in lines of no

more than 'width' columns, and return a list of wrapped lines. By

default, tabs in 'text' are expanded with string.expandtabs(), and

all other whitespace characters (including newline) are converted to

space. See TextWrapper class for available keyword args to customize

wrapping behaviour.

"""

w = TextWrapper(width=width, **kwargs)

return w.wrap(text)

textwrap.fill(text, width=70, **kwargs)def fill(text, width=70, **kwargs): """Fill a single paragraph of text, returning a new string. Reformat the single paragraph in 'text' to fit in lines of no more than 'width' columns, and return a new string containing the entire wrapped paragraph. As with wrap(), tabs are expanded and other whitespace characters converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour. “""

w = TextWrapper(width=width, **kwargs)

return w.fill(text)

對 text 中的單獨段落自動換行,並返回一個包含被自動換行段落的單獨字符串。 fill() 是以下語句的快捷方式

"\n".join(wrap(text, ...))


特別要說明的是,fill() 接受與 wrap() 完全相同的關鍵字參數。

textwrap.shorten(text, width, **kwargs)摺疊並截短給定的 text 以符合給定的 width。def shorten(text, width, **kwargs): """Collapse and truncate the given text to fit in the given width. The text first has its whitespace collapsed. If it then fits in the *width*, it is returned as is. Otherwise, as many words as possible are joined and then the placeholder is appended::

>>> textwrap.shorten("Hello world!", width=12)

'Hello world!'

>>> textwrap.shorten("Hello world!", width=11)

'Hello [...]'

"""

w = TextWrapper(width=width, max_lines=1, **kwargs)

return w.fill(' '.join(text.strip().split()))

首先將摺疊 text 中的空格(所有連續空格替換為單個空格)。 如果結果能適合 width 則將其返回。 否則將丟棄足夠數量的末尾單詞以使得剩餘單詞加 placeholder 能適合 width:

>>>

>>> textwrap.shorten("Hello world!", width=12)

'Hello world!'

>>>

textwrap.shorten("Hello world!", width=11)

'Hello [...]'

>>> textwrap.shorten("Hello world", width=10, placeholder="...")

'Hello...'

可選的關鍵字參數對應於 TextWrapper 的實際屬性,具體見下文。 請注意文本在被傳入 TextWrapper 的 fill() 函數之前會被摺疊,因此改變 tabsize, exand_tabs, drop_whitespace 和 replace_whitespace 的值將沒有任何效果。

3.4 新版功能.

textwrap.dedent(text)移除 text 中每一行的任何相同前綴空白符。這可以用來清除三重引號字符串行左側空格,而仍然在源碼中顯示為縮進格式。請注意製表符和空格符都被視為是空白符,但它們並不相等:以下兩行 " hello" 和 "\thello" 不會被視為具有相同的前綴空白符。例如def test(): # end first line with \ to avoid the empty line! s = '''\ hello world ''' print(repr(s)) # prints ' hello\n world\n ' print(repr(dedent(s))) # prints 'hello\n world\n'


textwrap.indent(text, prefix, predicate=None)將 prefix 添加到 text 中選定行的開頭。通過調用 text.splitlines(True) 來對行進行拆分。默認情況下,prefix 會被添加到所有不是隻由空白符(包括任何行結束符)組成的行。例如>>>

>>> s = 'hello\n\n \nworld' >>> indent(s, ' ') ' hello\n\n \n world'


可選的 predicate 參數可用來控制哪些行要縮進。 例如,可以很容易地為空行或只有空白符的行添加 prefix:

>>>

>>> print(indent(s, '+ ', lambda line: True))

+ hello

+

+

+ world


3.3 新版功能.

wrap(), fill() 和 shorten() 的作用方式為創建一個 TextWrapper 實例並在其上調用單個方法。 該實例不會被重用,因此對於要使用 wrap() 和/或 fill() 來處理許多文本字符串的應用來說,創建你自己的 TextWrapper 對象可能會更有效率。

文本最好在空白符位置自動換行,包括帶連字符單詞的連字符之後;長單詞僅在必要時會被拆分,除非
TextWrapper.break_long_words 被設為假值。

class textwrap.TextWrapper(**kwargs)TextWrapper 構造器接受多個可選的關鍵字參數。 每個關鍵字參數對應一個實例屬性,比如說wrapper = TextWrapper(initial_indent="* ")


就相當於

wrapper = TextWrapper()

wrapper.initial_indent = "* "


你可以多次重用相同的 TextWrapper 對象,並且你也可以在使用期間通過直接向實例屬性賦值來修改它的任何選項。

TextWrapper 的實例屬性(以及構造器的關鍵字參數)如下所示:

width(默認: 70) 自動換行的最大行長度。 只要輸入文本中沒有長於 width 的單個單詞,TextWrapper 就能保證沒有長於 width 個字符的輸出行。expand_tabs(默認: True) 如果為真值,則 text 中所有的製表符將使用 text 的 expandtabs() 方法擴展為空格符。

tabsize(默認: 8) 如果 expand_tabs 為真值,則 text 中所有的製表符將擴展為零個或多個空格,具體取決於當前列位置和給定的製表寬度。3.3 新版功能.replace_whitespace(default: True) 如果為真值,在製表符擴展之後、自動換行之前,wrap() 方法將把每個空白字符都替換為單個空格。 會被替換的空白字符如下:製表,換行,垂直製表,進紙和回車 ('\t\n\v\f\r')。註解如果 expand_tabs 為假值且 replace_whitespace 為真值,每個製表符將被替換為單個空格,這與製表符擴展是 不 一樣的。註解如果 replace_whitespace 為假值,在一行的中間有可能出現換行符並導致怪異的輸出。 因此,文本應當(使用 str.splitlines() 或類似方法)拆分為段落並分別進行自動換行。drop_whitespace(默認: True) 如果為真值,每一行開頭和末尾的空白字符(在包裝之後、縮進之前)會被丟棄。 但是段落開頭的空白字符如果後面不帶任何非空白字符則不會被丟棄。 如果被丟棄的空白字符佔據了一個整行,則該整行將被丟棄。initial_indent(默認: '') 將被添加到被自動換行輸出內容的第一行的字符串。 其長度會被計入第一行的長度。 空字符串不會被縮進。subsequent_indent(default: '') 將被添加到被自動換行輸出內容除第一行外的所有行的字符串。 其長度會被計入除行一行外的所有行的長度。
fix_sentence_endings(默認: False) 如果為真值,TextWrapper 將嘗試檢測句子結尾並確保句子間總是以恰好兩個空格符分隔。 對於使用等寬字體的文本來說通常都需要這樣。 但是,句子檢測算法並不完美:它假定句子結尾是一個小寫字母加字符 '.', '!' 或 '?' 中的一個,並可能帶有字符 '"' 或 "'",最後以一個空格結束。 此算法的問題之一是它無法區分以下文本中的 “Dr.”[...] Dr. Frankenstein's monster [...]


和以下文本中的 “Spot.”

[...] See Spot. See Spot run [...]


fix_sentence_endings 默認為假值。

Since the sentence detection algorithm relies on string.lowercase for the definition of “lowercase letter,” and a convention of using two spaces after a period to separate sentences on the same line, it is specific to English-language texts.

break_long_words(默認: True)

如果為真值,則長度超過 width 的單詞將被分開以保證行的長度不會超過 width。 如果為假值,超長單詞不會被分開,因而某些行的長度可能會超過 width。 (超長單詞將被單獨作為一行,以儘量減少超出 width 的情況。)

break_on_hyphens(默認: True) 如果為真值,將根據英語的慣例首選在空白符和複合詞的連字符之後自動換行。 如果為假值,則只有空白符會被視為合適的潛在斷行位置,但如果你確實不希望出現分開的單詞則你必須將 break_long_words 設為假值。 之前版本的默認行為總是允許分開帶有連字符的單詞。

max_lines(默認: None)

如果不為 None,則輸出內容將最多包含 max_lines 行,並使 placeholder 出現在輸出內容的末尾。3.4 新版功能.

placeholder(默認: ' [...]')

該文本將在輸出文本被截短時出現在文本末尾。

3.4 新版功能.

TextWrapper 還提供了一些公有方法,類似於模塊層級的便捷函數:wrap(text)對 text (字符串) 中的單獨段落自動換行以使每行長度最多為 width 個字符。 所有自動換行選項均獲取自 TextWrapper 實例的實例屬性。 返回由輸出行組成的列表,行尾不帶換行符。 如果自動換行輸出結果沒有任何內容,則返回空列表。fill(text)對 text 中的單獨段落自動換行並返回包含被自動換行段落的單獨字符串。


分享到:


相關文章: