'Programming'에 해당되는 글 16

  1. 2009.04.09 pickle in binary file
  2. 2009.04.01 "Short-circuit" conditional calls in Python
  3. 2009.01.30 multiply by logical values
  4. 2009.01.30 lambda
  5. 2009.01.29 dimension of matrix ( or array )
  6. 2009.01.29 create array in numpy
  7. 2009.01.20 numpy
  8. 2008.06.23 command Line Arguments
  9. 2008.06.23 pickle & unpickle
  10. 2008.05.11 function dic
Programming/Python | Posted by 알 수 없는 사용자 2009. 4. 9. 22:35

pickle in binary file

Pickler Protocols and cPickle

In recent Python releases, the pickler introduced the notion of protocolsstorage formats for pickled data. Specify the desired protocol by passing an extra parameter to the pickling calls (but not to unpickling calls: the protocol is automatically determined from the pickled data):

pickle.dump(object, file, protocol)

Pickled data may be created in either text or binary protocols. By default, the storage protocol is text (also known as protocol 0). In text mode, the files used to store pickled objects may be opened in text mode as in the earlier examples, and the pickled data is printable ASCII text, which can be read (it's essentially instructions for a stack machine).

The alternative protocols (protocols 1 and 2) store the pickled data in binary format and require that files be opened in binary mode (e.g., rb, wb). Protocol 1 is the original binary format; protocol 2, added in Python 2.3, has improved support for pickling of new-style classes. Binary format is slightly more efficient, but it cannot be inspected. An older option to pickling calls, the bin argument, has been subsumed by using a pickling protocol higher than 0. The pickle module also provides a HIGHEST_PROTOCOL variable that can be passed in to automatically select the maximum value.

One note: if you use the default text protocol, make sure you open pickle files in text mode later. On some platforms, opening text data in binary mode may cause unpickling errors due to line-end formats on Windows:

>>> f = open('temp', 'w')                  # text mode file on Windows
>>> pickle.dump(('ex', 'parrot'), f) # use default text protocol
>>> f.close( )
>>>
>>> pickle.load(open('temp', 'r')) # OK in text mode
('ex', 'parrot')
>>> pickle.load(open('temp', 'rb')) # fails in binary
Traceback (most recent call last):
File "<pyshell#337>", line 1, in -toplevel-
pickle.load(open('temp', 'rb'))
...lines deleted...
ValueError: insecure string pickle

One way to sidestep this potential issue is to always use binary mode for your files, even for the text pickle protocol. Since you must open files in binary mode for the binary pickler protocols anyhow (higher than the default 0), this isn't a bad habit to get into:

>>> f = open('temp', 'wb')                 # create in binary mode
>>> pickle.dump(('ex', 'parrot'), f) # use text protocol
>>> f.close( )
>>>
>>> pickle.load(open('temp', 'rb'))
('ex', 'parrot')
>>> pickle.load(open('temp', 'r'))
('ex', 'parrot')
Programming/Python | Posted by 알 수 없는 사용자 2009. 4. 1. 04:54

"Short-circuit" conditional calls in Python

# Normal statement-based flow control
if <cond1>:   func1()
elif <cond2>: func2()
else:         func3()

# Equivalent "short circuit" expression
(<cond1> and func1()) or (<cond2> and func2()) or (func3())

# Example "short circuit" expression
>>> x = 3
>>> def pr(s): return s
>>> (x==1 and pr('one')) or (x==2 and pr('two')) or (pr('other'))
'other'
>>> x = 2
>>> (x==1 and pr('one')) or (x==2 and pr('two')) or (pr('other'))
'two'

from :http://gnosis.cx/publish/programming/charming_python_13.html

Programming/Python | Posted by 알 수 없는 사용자 2009. 1. 30. 17:28

multiply by logical values

>>> 20 * True
20
>>> 20 * False
0
Programming/Python | Posted by 알 수 없는 사용자 2009. 1. 30. 17:27

lambda

>>> def f ( x ) : return x**2
>>> g = lambda x : x **2

>>> h = lambda x: ( x < 1 ) or x * f(x-1)          #x!


Programming/Python | Posted by 알 수 없는 사용자 2009. 1. 29. 22:27

dimension of matrix ( or array )

>>> U = random.rand ( 200, 20 )
>>> shape ( U )
( 200, 20 )

>>> size ( U ) #return total element of the matrix ( array )
4000
Programming/Python | Posted by 알 수 없는 사용자 2009. 1. 29. 22:23

create array in numpy

array ( sequence, dtype = None, copy = True, order = None, subok = True, ndmin=True )
>>> from numpy import *
>>> a = array ( [ 1, 2, 3 ], dtype = float )
>>> a
array ( [ 1., 2., 3. ] )

Programming/Python | Posted by 알 수 없는 사용자 2009. 1. 20. 14:41

numpy

random matrix 생성 :
numpy.random.rand ( d0, d1, d2, ... )
ex ) : numpy.random.rand ( 2, 3 )
 >>> array([[ 0.45133966,  0.72357161,  0.31706311],
                    [ 0.15414275,  0.0952978 ,  0.35952268]])

Programming/Python | Posted by 알 수 없는 사용자 2008. 6. 23. 12:13

command Line Arguments

sys.argv
is an array that contains the command-line arguments passed to the program

for example,
>> python file2DIC -f CityU.utf8.seg -d CityU.DIC

then the value of sys.argv is :
sys.argv [ 0 ] = "file2DIC"
sys.argv [ 1 ] = "-f"
sys.argv [ 2 ] = "CityU.utf8.seg"
sys.argv [ 3 ] = "-d"
sys.argv [ 4 ] = "CityU.DIC"

remember, if you'd like to use it in python, don't forget to add the following lines in your programming:
import sys
Programming/Python | Posted by 알 수 없는 사용자 2008. 6. 23. 12:10

pickle & unpickle

import pickle

# pickling list
f = open ( "pickle.dat", "w" )
mixList = [ 'one', 1 'two', 2 ]
pickle.dump ( mixList, f )
f.close ()

#unpickling
f = open ( "pickle.dat", "r" )
mixList = pickle.load ( f )
print mixList
f.close ()
Programming/Python | Posted by 알 수 없는 사용자 2008. 5. 11. 02:07

function dic

Functions as object

switch = {
            'one' : function1,
            'two' : function2,
            'three' : function3
            }

try:
    result = switch[choice]
except KeyError :
    print 'I didn't understand your choice.'
else :
    result ()