Python/2.7 information

dictionary 예쁘게 출력하기 + 한글 그대로 출력

qkqhxla1 2019. 10. 23. 14:25

특정 사이트에서 api를 사용해서 어떤 정보를 가져올 경우 요즘은 대부분 json의 형태로 결과가 나온다. 그 정보를 가져다가 써야 할 경우에 json.loads같은거로 딕셔너리로 가져와서 쓰는데, api결과값의 구조가 많이 복잡할 경우 분석해서 프로그래밍을 하기가 힘들다. (특정 값이 딕셔너리의 3,4단 안에 있을 경우 키를 찾아서 들어가기가 어렵다는 말. 또는 눈으로 볼수 없어 구조 분석이 힘들다는 말.)

 

예를 들면 혼자서 하는 프로젝트를 하려고 어떤 쇼핑몰 사이트에서 상품정보를 가지고와서 사용하려고 하는데 api의 결과값이 복잡한 경우가 있다. api의 결과값이 복잡할 경우 쇼핑몰의 상품정보를 가지고 오려고 하는데 그 상품정보가 딕셔너리의 어디의 어디를 찾아서 들어가야하는지도 복잡하고, json.loads로 딕셔너리로 만들어버릴 경우 인코딩이 되므로 pprint로 출력해도 인코딩된 결과값이 나와서 컨트롤+f로 검색할 수도 없다. 이 경우에..

 

http://mcchae.egloos.com/11076302

https://stackoverflow.com/questions/3229419/how-to-pretty-print-nested-dictionaries

등등에 나온 방법을 사용할 수 있다.

 

난 위에 지훈현서님이 만들어놓은 방법이 좋은듯 싶다. 예쁘게 출력해주면서 한글도 보이게 출력됨.(문제시 삭제)

import pprint
class MyPrettyPrinter(pprint.PrettyPrinter):
	def format(self, _object, context, maxlevels, level):
		if isinstance(_object, unicode):
			return "'%s'" % _object.encode('utf8'), True, False
		elif isinstance(_object, str):
			_object = unicode(_object,'utf8')
			return "'%s'" % _object.encode('utf8'), True, False
		return pprint.PrettyPrinter.format(self, _object, context, maxlevels, level)

~~~~~
print MyPrettyPrinter().pformat(info)


python3

import pprint

class MyPrettyPrinter(pprint.PrettyPrinter):
    def format(self, _object, context, maxlevels, level):
        if isinstance(_object, str):
            return "'%s'" % _object.encode('utf8'), True, False
        return pprint.PrettyPrinter.format(self, _object, context, maxlevels, level)

% 물론 ide의 디버깅 모드에서 변수 내부의 정보를 출력할 수 있지만 직관적이지 못하다.

'Python > 2.7 information' 카테고리의 다른 글

why use namedtuple  (2) 2020.12.26
json.loads 에러시 위치 찾는 방법 꿀팁  (2) 2019.12.02
timezone 설정 모듈.  (0) 2019.09.28
python re search with newline  (0) 2019.09.23
파일 옮기는 꿀팁. (SimpleHTTPServer)  (0) 2019.08.01