pprint的定制,ordereddict相关

by windviki
2013/04/24
 
1. pprint无法为OrderedDict正常显示类似dict的层次结构:
In [ 1] : from collections import OrderedDict

In [ 2] : import pprint

In [ 3] : od = OrderedDict([( "key1", 100), ( "I'm key2", 2), ( "a key3", 3)])

In [ 4] : d = dict([( "key1", 100), ( "I'm key2", 2), ( "a key3", 3)])

In [ 5] : pprint.pprint(od)
OrderedDict([( 'key1', 100), ( "I'm key2", 2), ( 'a key3', 3)])

In [ 6] : pprint.pprint(d)
{ "I'm key2" : 2, 'a key3' : 3, 'key1' : 100}
 
2.pprint无法将unicode或者utf8字符正确的显示和打印,总是会format成16进制的格式。
In [ 7] : od[ "测试"] = unicode( "中文", "utf-8")

In [ 8] : pprint.pprint(od)
OrderedDict([( 'key1', 100), ( "I'm key2", 2), ( 'a key3', 3), ( '\xe6\xb5\x8b\xe8\xaf\x95', u '\u4e2d\u6587')])
 
3.综上,需要对pprint进行patch才能满足需求。
#*- coding: utf-8 *-
#####################################################################
#    Created:    2012/7/27   13:33
#    Filename:   printod.py
#    Author:     viki
#    Copyright:  
#********************************************************************
#    Comments:    
#
#    UpdateLogs:    
#####################################################################
import os
import sys
import json
import types
from collections import OrderedDict
OrderedDict. __repr__ = dict. __repr__

def _sorted(iterable) :
     return iterable

import pprint
pprint._sorted = _sorted

class MyPrettyPrinter(pprint.PrettyPrinter) :
     def __init__( self, encoding = "utf-8", indent = 1, width = 80, depth = None, stream = None) :
         self._encoding = encoding
        pprint.PrettyPrinter. __init__(self, indent, width, depth, stream)

     def _format( self, object, stream, indent, allowance, context, level) :
         if type(object) == types.StringType :
            object = object.decode( self._encoding)
         return pprint.PrettyPrinter._format( self, object, stream, indent, allowance, context, level)

     def format( self, object, context, maxlevels, level) :
         if type(object) == types.StringType :
             return ( "\"%s\"" % object.decode().encode( self._encoding), True, False)
         if isinstance(object, unicode) :
             return ( "\"%s\"" % object.encode( self._encoding), True, False)
         return pprint.PrettyPrinter.format( self, object, context, maxlevels, level)

od = OrderedDict([
    ( "hello", u "unicode文字"), 
    ( "a", "中文2"), 
    ( "测试", 3), 
    ( "od", OrderedDict([( "test2", 1), ( "test1第二个keyの", 2)])),
    ( "xx", dict([( "dict1", 1), ( "dict2", u "无序字典"), ( "dict3", [ 1, 2, 3, ( 4, 100)])])),
    ])

with open( "printod.txt", "w+") as fd :
    fd.write( "#*- coding: utf-8 *-\n")
    fd.write(MyPrettyPrinter().pformat(od))


来自为知笔记(Wiz)Time=2013-04-24 14:12:34


你可能感兴趣的:(pprint的定制,ordereddict相关)