Python中使用pprint函數(shù)進行格式化輸出的教程
pprint – 美觀打印
作用:美觀打印數(shù)據(jù)結(jié)構(gòu)
pprint 包含一個“美觀打印機”,用于生成數(shù)據(jù)結(jié)構(gòu)的一個美觀視圖。格式化工具會生成數(shù)據(jù)結(jié)構(gòu)的一些表示,不僅可以由解釋器正確地解析,而且便于人類閱讀。輸出盡可能放在一行上,分解為多行時則需要縮進。
以下實例用用到的data包含一下數(shù)據(jù)
data = [(1,{'a':'A','b':'B','c':'C','d':'D'}),
(2,{'e':'E','f':'F','g':'G','h':'H',
'i':'I','j':'J','k':'K','l':'L'
}),
]
1、 打印
要使用這個模塊,最簡單的方法就是利用pprint()函數(shù)
from pprint import pprint print 'PRINT:' print data print print 'PPRINT:' pprint(data)
運行結(jié)果:
PRINT:
[(1, {'a': 'A', 'c': 'C', 'b': 'B', 'd': 'D'}), (2, {'e': 'E', 'g': 'G', 'f': 'F', 'i': 'I', 'h': 'H', 'k': 'K', 'j': 'J', 'l': 'L'})]
PPRINT:
[(1, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}),
(2,
{'e': 'E',
'f': 'F',
'g': 'G',
'h': 'H',
'i': 'I',
'j': 'J',
'k': 'K',
'l': 'L'})]
pprint()格式化一個對象,并把它寫至一個數(shù)據(jù)流,這個數(shù)據(jù)流作為參數(shù)傳入(或者是默認(rèn)的sys.stdout)
注意為什么第二個字典中會顯示一豎列,因為pprint打印支持8個對象以上的豎列打印
2、 格式化
格式化一個數(shù)據(jù)結(jié)構(gòu)而不把它直接寫至一個流(例如用于日志記錄),可以使用pformat()來構(gòu)造一個字符串表示。
import logging
from pprint import pformat
logging.basicConfig(level = logging.DEBUG,
format = '%(levelname)-8s %(message)s',
)
logging.debug('Logging pformatted data')
formatted = pformat(data)
for line in formatted.splitlines():
logging.debug(line.rstrip())
運行結(jié)果:
DEBUG Logging pformatted data
DEBUG [(1, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}),
DEBUG (2,
DEBUG {'e': 'E',
DEBUG 'f': 'F',
DEBUG 'g': 'G',
DEBUG 'h': 'H',
DEBUG 'i': 'I',
DEBUG 'j': 'J',
DEBUG 'k': 'K',
DEBUG 'l': 'L'})]
然后可以單獨低打印格式化的字符串或者計入日志
splitlines() 按行分割()
rstrip()去除右邊的空格 lstrip()去除左邊的空格 strip()去除兩邊空格。默認(rèn)為去除空格,也可以傳入需要從兩邊或者其中一邊去除的字符,如strip(‘a(chǎn)')就是去除字符串兩邊的字符'a'
3、 任意類
如果定制類定義了一個__repr__()方法,pprint()使用的PrettyPrinter類還可以處理這些定制類。
from pprint import pprint
class node(object):
def __init__(self,name,contents =[]):
self.name = name
self.contents = contents[:]
def __repr__(self):
return ('node(' + repr(self.name) + ',' +
repr(self.contents) + ')'
)
trees = [node('node-1'),
node('node-2',[node('node-2-1')]),
node('node-3',[node('node-3-1')]),
]
pprint(trees)
運行結(jié)果:
[node('node-1',[]),
node('node-2',[node('node-2-1',[])]),
node('node-3',[node('node-3-1',[])])]
由PrettyPrinter組合嵌套對象的表示,從而返回完整字符串表示。
4、 遞歸
遞歸數(shù)據(jù)結(jié)構(gòu)有指向原數(shù)據(jù)源的引用來表示,形式為<Recursion on typename with id=number>。
from pprint import pprint local_data = ['a','b',1,2] local_data.append(local_data) print 'id(local_data) =>',id(local_data) pprint(local_data) print local_data
運行結(jié)果:
id(local_data) => 47458332363520 ['a', 'b', 1, 2, <Recursion on list with id=47458332363520>] ['a', 'b', 1, 2, [...]]
在這個例子中,列表local_data增加到了其自身,這會創(chuàng)建一個遞歸引用
內(nèi)置函數(shù)id()作用是獲得對象的id值,理論上講每個對象都有一個id值,如果是整數(shù)和字符串((相對較小的時候)),那么相同的值會有相同的id值,但是如果是類,及時相同也會有不同的id值。測試如下:
#int or float or lon 都一樣(比較小的時候)
a = 65464131311513l
b = 65464131311513l
c = 65464131311513l
print id(a)
print id(b)
print id(c)
print
a = '12312312'
b = '12312312'
c = '12312312'
print id(a)
print id(b)
print id(c)
print
a = 65464131311513l*11
b = 65464131311513l*11
c = 65464131311513l*11
print id(a)
print id(b)
print id(c)
print
a = '12312312'*11
b = '12312312'*11
c = '12312312'*11
print id(a)
print id(b)
print id(c)
print
class Test(object):
def __init__(self):
pass
a = Test()
b = Test()
c = Test()
print id(a)
print id(b)
print id(c)
print
測試結(jié)果:
47010342174992 47010342174992 47010342174992 47010343272096 47010343272096 47010343272096 47010343261568 47010343261648 47010343261688 47010343200944 47010343199152 47010343202352 47010343252304 47010343252944 47010343253008
5、 限制嵌套輸出
對于非常深的數(shù)據(jù)結(jié)構(gòu),可能不要求輸出包含所有細(xì)節(jié)。有可能數(shù)據(jù)沒有是當(dāng)?shù)馗袷交?,也可能格式化文本過大而無法管理,或者默寫數(shù)據(jù)時多余的。
from pprint import pprint print 'depth 1 :' pprint(data,depth=1) print print 'depth 2 :' pprint(data,depth=2) print print 'depth 3 :' pprint(data,depth=3)
運行結(jié)果:
depth 1 :
[(...), (...)]
depth 2 :
[(1, {...}), (2, {...})]
depth 3 :
[(1, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}),
(2,
{'e': 'E',
'f': 'F',
'g': 'G',
'h': 'H',
'i': 'I',
'j': 'J',
'k': 'K',
'l': 'L'})]
使用depth參數(shù)可以控制美觀打印機遞歸處理嵌套數(shù)據(jù)結(jié)構(gòu)的深度。輸出中未包含的層次由一個省略號表示
6、 控制輸出寬度
格式化文本的默認(rèn)輸出寬度為80列。要調(diào)整這個寬度,可以再pprint()中使用參數(shù)width。
from pprint import pprint for width in [80,5]: print 'WIDTH = ', width pprint(data,width = width) print
運行結(jié)果:
WIDTH = 80
[(1, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}),
(2,
{'e': 'E',
'f': 'F',
'g': 'G',
'h': 'H',
'i': 'I',
'j': 'J',
'k': 'K',
'l': 'L'})]
WIDTH = 5
[(1,
{'a': 'A',
'b': 'B',
'c': 'C',
'd': 'D'}),
(2,
{'e': 'E',
'f': 'F',
'g': 'G',
'h': 'H',
'i': 'I',
'j': 'J',
'k': 'K',
'l': 'L'})]
寬度大小不能適應(yīng)格式化數(shù)據(jù)結(jié)構(gòu)時,如果斬斷或轉(zhuǎn)行會引入非法的語法,就不會進行截斷或轉(zhuǎn)行。
相關(guān)文章
pytorch-神經(jīng)網(wǎng)絡(luò)擬合曲線實例
今天小編就為大家分享一篇pytorch-神經(jīng)網(wǎng)絡(luò)擬合曲線實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01
用Python實現(xiàn)數(shù)據(jù)的透視表的方法
今天小編就為大家分享一篇用Python實現(xiàn)數(shù)據(jù)的透視表的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11
Python3爬蟲里關(guān)于識別微博宮格驗證碼的知識點詳解
在本篇文章里小編給大家分享了關(guān)于Python3爬蟲里關(guān)于識別微博宮格驗證碼的知識點,有興趣的朋友們可以參考下。2020-07-07
scrapy與selenium結(jié)合爬取數(shù)據(jù)(爬取動態(tài)網(wǎng)站)的示例代碼
這篇文章主要介紹了scrapy與selenium結(jié)合爬取數(shù)據(jù)的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09

