developer tip

Python에서 산 세척 이해하기

optionbox 2021. 1. 6. 08:03
반응형

Python에서 산 세척 이해하기


저는 최근에 절인 형태로 사전 (각 키가 목록을 참조하는 곳)을 넣어야하는 과제를 받았습니다. 유일한 문제는 절임 형태가 무엇인지 전혀 모른다는 것입니다. 누구든지이 개념을 배우는 데 도움이되는 좋은 리소스의 올바른 방향을 알려줄 수 있습니까?


pickle 모듈은 Python 객체 구조를 직렬화 및 역 직렬화하기위한 기본적이지만 강력한 알고리즘을 구현합니다.

Pickling- Python 객체 계층 구조가 바이트 스트림으로 변환되고 Unpickling- 역 연산으로 바이트 스트림이 객체 계층 구조로 다시 변환됩니다.

산세 (및 산세 해제)는 직렬화 , 마샬링 또는 평탄화 라고도 합니다.

import pickle

data1 = {'a': [1, 2.0, 3, 4+6j],
         'b': ('string', u'Unicode string'),
         'c': None}

selfref_list = [1, 2, 3]
selfref_list.append(selfref_list)

output = open('data.pkl', 'wb')

# Pickle dictionary using protocol 0.
pickle.dump(data1, output)

# Pickle the list using the highest protocol available.
pickle.dump(selfref_list, output, -1)

output.close()

절인 파일에서 읽으려면-

import pprint, pickle

pkl_file = open('data.pkl', 'rb')

data1 = pickle.load(pkl_file)
pprint.pprint(data1)

data2 = pickle.load(pkl_file)
pprint.pprint(data2)

pkl_file.close()

출처-https: //docs.python.org/2/library/pickle.html


Pickling은 파이썬 객체의 관련 상태를 문자열로 변환하는 데 사용할 수있는 미니 언어입니다.이 문자열은 객체를 고유하게 나타냅니다. 그런 다음 (un) pickling을 사용하여 문자열을 발견 한 저장된 상태에서 개체를 "재구성"하여 문자열을 라이브 개체로 변환 할 수 있습니다.

>>> import pickle
>>> 
>>> class Foo(object):
...   y = 1
...   def __init__(self, x):
...     self.x = x
...     return
...   def bar(self, y):
...     return self.x + y
...   def baz(self, y):
...     Foo.y = y  
...     return self.bar(y)
... 
>>> f = Foo(2)
>>> f.baz(3)
5
>>> f.y
3
>>> pickle.dumps(f)
"ccopy_reg\n_reconstructor\np0\n(c__main__\nFoo\np1\nc__builtin__\nobject\np2\nNtp3\nRp4\n(dp5\nS'x'\np6\nI2\nsb."

여기서 볼 수있는 것은 pickle이 클래스의 소스 코드를 저장하지 않고 클래스 정의에 대한 참조를 저장한다는 것입니다. 기본적으로 선택한 문자열을 거의 읽을 수 있습니다. "인수가 정의 된 클래스 인 copy_reg의 재구성자를 호출 __main__.Foo한 다음 다른 작업을 수행합니다 "라고 (대략 번역됨) 말합니다 . 다른 것은 인스턴스의 저장된 상태입니다. 더 자세히 살펴보면 "문자열 x"가 "정수 2"(대략 :)로 설정되어 있음을 추출 할 수 있습니다 S'x'\np6\nI2. 이것은 실제로 사전 항목에 대한 절인 문자열의 잘린 부분입니다 . dict존재 f.__dict__, 즉 {'x': 2}. 에 대한 소스 코드를 보면 pickle각 유형의 객체 및 작업에 대한 파이썬에서 피클 된 바이트 코드로의 번역이 매우 명확하게 제공됩니다.

Note also that there are different variants of the pickling language. The default is protocol 0, which is more human-readable. There's also protocol 2, shown below (and 1,3, and 4, depending on the version of python you are using).

>>> pickle.dumps([1,2,3])
'(lp0\nI1\naI2\naI3\na.'
>>> 
>>> pickle.dumps([1,2,3], -1)
'\x80\x02]q\x00(K\x01K\x02K\x03e.'

Again, it's still a dialect of the pickling language, and you can see that the protocol 0 string says "get a list, include I1, I2, I3", while the protocol 2 is harder to read, but says the same thing. The first bit \x80\x02 indicates that it's protocol 2 -- then you have ] which says it's a list, then again you can see the integers 1,2,3 in there. Again, check the source code for pickle to see the exact mapping for the pickling language.

To reverse the pickling to a string, use load/loads.

>>> p = pickle.dumps([1,2,3])
>>> pickle.loads(p)
[1, 2, 3]

Pickling is just serialization: putting data into a form that can be stored in a file and retrieved later. Here are the docs on the pickle module:

http://docs.python.org/release/2.7/library/pickle.html


http://docs.python.org/library/pickle.html#example

import pickle

data1 = {'a': [1, 2.0, 3, 4+6j],
         'b': ('string', u'Unicode string'),
         'c': None}

selfref_list = [1, 2, 3]
selfref_list.append(selfref_list)

output = open('data.pkl', 'wb')

# Pickle dictionary using protocol 0.
pickle.dump(data1, output)

# Pickle the list using the highest protocol available.
pickle.dump(selfref_list, output, -1)

output.close()

Pickling in Python is used to serialize and de-serialize Python objects, like dictionary in your case. I usually use cPickle module as it can be much faster than the Pickle module.

import cPickle as pickle    

def serializeObject(pythonObj):
    return pickle.dumps(pythonObj, pickle.HIGHEST_PROTOCOL)

def deSerializeObject(pickledObj):
    return pickle.loads(pickledObj)

The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream is converted back into an object hierarchy. Pickling (and unpickling) is alternatively known as “serialization”, “marshaling,” or “flattening”, however, to avoid confusion, the terms used here are “pickling” and “unpickling”.

The pickle module has an optimized cousin called the cPickle module. As its name implies, cPickle is written in C, so it can be up to 1000 times faster than pickle. However, it does not support subclassing of the Pickler() and Unpickler() classes, because in cPickle these are functions, not classes. Most applications have no need for this functionality and can benefit from the improved performance of cPickle. Other than that, the interfaces of the two modules are nearly identical; the common interface is described in this manual and differences are pointed out where necessary. In the following discussions, we use the term “pickle” to collectively describe the pickle and cPickle modules.

The data streams the two modules produce are guaranteed to be interchangeable.


Pickle > Serielization > binary stream

import pickle
f = open("data.txt","wb")
dct = {"name":"Ravi", "age":23, "Gender":"M","marks":75}
pickle.dump(dct,f)
f.close()

UnPickle > deSerielization

import pickle
f = open("data.txt","rb")
d = pickle.load(f)
print (d)
f.close()

Pickling

>>> from pickle import dump
>>> dct = {"name":"Ravi", "age":23, "Gender":"M","marks":75}
>>> dctstring = dumps(dct)
>>> dctstring
b'\x80\x03}q\x00(X\x04\x00\x00\x00nameq\x01X\x04\x00\x00\x00Raviq\x02X\x03\x00\x00\x00ageq\x03K\x17X\x06\x00\x00\x00Genderq\x04X\x01\x00\x00\x00Mq\x05X\x05\x00\x00\x00marksq\x06KKu.'

Unpickling

>>> from pickle import load
>>> dct = loads(dctstring)
>>> dct
{'name': 'Ravi', 'age': 23, 'Gender': 'M', 'marks': 75}

ReferenceURL : https://stackoverflow.com/questions/7501947/understanding-pickling-in-python

반응형