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!'
>>>
'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 會被添加到所有不是隻由空白符(包括任何行結束符)組成的行。例如>>>
可選的 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() 方法擴展為空格符。
和以下文本中的 “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 中的單獨段落自動換行並返回包含被自動換行段落的單獨字符串。