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))




转载于:https://www.cnblogs.com/windviki/archive/2013/05/19/3087702.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值