Sunday, November 11, 2012

Notes of Python

。。。。。

.
prs22
prs22b

prs42
prs43

prs52
prs53

..
.
toolDoc2
__init__

dict21
dict22
dict23n -1
dict23n -2
dict23n -3
dict24


..
...


25 comments:

  1. prs43

    $$ Types of Classes in programming

    A utility/tools, not saving the external data, or the related data
    B utility/tools, saving the external data, or the related data
    C functions, serving for the specific external data
    D functions, serving the internal data

    Module, contains
    IMPORT section
    class dummy(): pass
    p = dummy() # global var
    def main():
    CLASSES section
    class doc2C():
    helpT=[0]
    lessonT=[0]
    i6c=toolDoc2.info6C(self)
    main()


    $$ Class Oriented

    def __init__(self): pass
    # main() part, to use classObjName.var; this is more convenience
    # in __inti__, have to use self.var; this is more clas-oriented
    # def __new__(cls): pass # for inheritance of multi-generation, multi-parent
    # def __call__(self): pass # for mainCObj()
    # def __init__(self): pass # for post-instantiation of object


    $$ Loading Chinese py file

    # from prs2ndu8 import *
    # prs2ndu8.py saved in utf-8
    # succeed, but require : str.decode("utf8")
    # add coding: utf-8 ; succeed in IMPORT; no need of decode()
    # from prs2ndu import *
    # prs2ndu.py saved in Unicode; fail in IMPORT
    # from prs2ndub import *
    # prs2ndu.py saved in Unicode big endian; fail in IMPORT
    # from prs2ndasc import *
    # prs2ndasc.py saved in ascii/ANSI endian; fail in IMPORT
    # add coding: cp936/gbk ; fail in IMPORT
    # add coding: utf-8 ; succeed in IMPORT



    $$ List

    pop([id]); remove(value);
    append(value); extend(list); insert(id, value);
    index(value); count(value); reverse(); sort();
    del list[:]/all; del [pos:stop]

    tuple
    a = (1,2), (3,4) >>> a == ((1,2), (3,4))
    a = 1, >>> a == (1,)
    a,b = (1,2) >>> a==1; b==2
    a,b = 1,2 >>> a==1; b==2
    (a,b) = (1,2) >>> a==1; b==2

    list("abc") >>> ["a","b","c"]
    tuple("abc") >>> ("a","b","c")

    """
    # END of LESSON text string


    helpT[0] = """

    $$ import prs32

    class parseClauseC():
    thisP = p
    def __init__():
    def intoSentence(self):
    def formPhrase(self, tt):
    def deleteChinese(self, line):
    def initWord(self):


    $$ Structure of classes, functions

    import toolDoc2, re
    # from prs2ndasc import dict6

    class dummy(): pass
    p = dummy() # var; global passing channel
    pw = dummy() # word, suffix, prefix to tell the part of speech
    text2 = ""

    def main():
    def main6():
    def main5():
    def test():

    class transferFile():
    def workLines (self, inFile, outFile):
    def lineToTuple(self, line):

    class fileOpr6():
    def openFile(self, fileNameStr):
    def closeFile(self):

    def initGlobal():

    ReplyDelete
  2. prs53

    $$ Function Closure

    def a(): def b(): print x; pass; x = 100; return b; c = a()
    # c=a() by return inner_func : closure
    # inner var can be accessed by b()


    $$ Exception Management

    try: do_someting
    ecept: do_exception
    finally: do_finally


    class manager():
    def __init__(self): pass
    def __enter__(self): pass # or, return AS_attribute
    def __exit__(self [, exc_type, exc_value, traceback]):
    do_FINALLY
    if tracback: do_exception
    pass
    with manager():
    DO_something

    @decorator # if deco is a class
    # @ will invoke deco.__init__()
    # declare __init__(self,func): self.func=func;
    # func() is invoked, then instead, deco.__call__() is invoked
    # @ :: func=deco.__call__
    @decorator # if deco is a function
    # def deco(f): def f2(): pass; (f2.__name__=f.__name__;) return f2
    # def f2(*args, **kwargs): return f(*args, **kwargs);
    # def f2(*args, **kwargs): f(*args, **kwargs);
    # @decon :: fucn=deco(func)

    __new__(cls)
    __init__(self [,args])
    __call__(self [, args]) # obj()
    __repr__(self) # obj, repr(obj)
    __str__(self) # str(obj)
    __enter__() # for with statement
    __exit__() # for with statement
    __del__(self) # del obj

    decorator :
    add pre- and post- functions, even replace the original
    work on only one function
    with statement :
    exception + decorator (will not replace the original)
    work on many statements
    try..finally : make things clear; with statment makes clean
    try..except : alternative to if..else



    $$ Sort

    L.sort(cmpFUNC=None, keyFUNC=None, reverse=False)

    L = [{1:5,3:4},{1:3,6:3},{1:1,2:4,5:6},{1:9}]
    def f2(a,b):
    print a[1],b[1] # get the value, {1:5}[1]==5
    return a[1]-b[1]
    L.sort(cmp=f2)

    L.sort() # retrun a new L
    L2 = sorted(L)




    $$ Class Oriented

    def __init__(self): pass
    # main() part, to use classObjName.var; this is more convenience
    # in __inti__, have to use self.var; this is more clas-oriented
    # def __new__(cls): pass # for inheritance of multi-generation, multi-parent
    # def __call__(self): pass # for mainCObj()
    # def __init__(self): pass # for post-instantiation of object


    $$ Loading Chinese py file

    # from prs2ndu8 import *
    # prs2ndu8.py saved in utf-8
    # succeed, but require : str.decode("utf8")
    # add coding: utf-8 ; succeed in IMPORT; no need of decode()
    # from prs2ndu import *
    # prs2ndu.py saved in Unicode; fail in IMPORT
    # from prs2ndub import *
    # prs2ndu.py saved in Unicode big endian; fail in IMPORT
    # from prs2ndasc import *
    # prs2ndasc.py saved in ascii/ANSI endian; fail in IMPORT
    # add coding: cp936/gbk ; fail in IMPORT
    # add coding: utf-8 ; succeed in IMPORT



    $$ List

    pop([id]); remove(value);
    append(value); extend(list); insert(id, value);
    index(value); count(value); reverse(); sort();
    del list[:]/all; del [pos:stop]

    tuple
    a = (1,2), (3,4) >>> a == ((1,2), (3,4))
    a = 1, >>> a == (1,)
    a,b = (1,2) >>> a==1; b==2
    a,b = 1,2 >>> a==1; b==2
    (a,b) = (1,2) >>> a==1; b==2

    list("abc") >>> ["a","b","c"]
    tuple("abc") >>> ("a","b","c")

    ReplyDelete
  3. prs22

    $$ Loading Chinese py file

    # from prs2ndu8 import *
    # prs2ndu8.py saved in utf-8
    # succeed, but require : str.decode("utf8")
    # add coding: utf-8 ; succeed in IMPORT; no need of decode()
    # from prs2ndu import *
    # prs2ndu.py saved in Unicode; fail in IMPORT
    # from prs2ndub import *
    # prs2ndu.py saved in Unicode big endian; fail in IMPORT
    # from prs2ndasc import *
    # prs2ndasc.py saved in ascii/ANSI endian; fail in IMPORT
    # add coding: cp936/gbk ; fail in IMPORT
    # add coding: utf-8 ; succeed in IMPORT



    $$ List

    pop([id]); remove(value);
    append(value); extend(list); insert(id, value);
    index(value); count(value); reverse(); sort();
    del list[:]/all; del [pos:stop]

    tuple
    a = (1,2), (3,4) >>> a == ((1,2), (3,4))
    a = 1, >>> a == (1,)
    a,b = (1,2) >>> a==1; b==2
    a,b = 1,2 >>> a==1; b==2
    (a,b) = (1,2) >>> a==1; b==2

    list("abc") >>> ["a","b","c"]
    tuple("abc") >>> ("a","b","c")

    ReplyDelete
  4. prs22b -1

    $$ Chome, Python Shell

    C:\Documents and Settings\Administrator\Local Settings\Application Data\ \
    Google\Chrome\User Data\Default\Extensions\ \
    gdiimmpmdoofmahingpgabiikimjgcia\2.2.2_0\extern\ \
    python\closured\include\python2.7

    python\closured\lib\python2.7\plat-linux2
    python\reloop-closured\lib\python2.7\plat-linux2
    python\unclosured\lib\python2.7\plat-linux2

    sys.path
    ['', 'lib/python27.zip',
    '/lib/python2.7/',
    '/lib/python2.7/plat-linux3',
    '/lib/python2.7/lib-tk',
    '/lib/python2.7/lib-old',
    '/lib/python2.7/lib-dynload']


    $$ Class Study

    SUPERclas = super(THISclassNAME, self)

    Find the caller of function ::
    import inspect
    inspect.stack()[1][3] # this function
    inspect.stack()[2][3] # caller function

    __new__(cls [, *args, **kwargs])
    invoked before instancation
    deal with class inheritance;
    track of superclasses, override issue
    return object.__new__(cls, *args, **kwargs)
    for multiple inheritance ::
    objList[0].__dict__.update(copy.deepcopy(obj.__dict__))
    cls : can be replaced by any id: cls2, typ
    __init__(self [, arg1, arg2])
    invoked after instancation
    deal with class arguments, properties,
    initiation
    to set initial values to properties,
    to run some functions
    __call__(self [, arg1, arg2])
    invoked when the object/instance is used as a function


    $$ String Replacement

    STRING.replace(old_sub, new_sub [, max])

    re.sub(r"RE", repl, STRING, count=0, flags=0)
    # r"" means "\"; or "\\"
    # works woth ()(), groups >> \1, \2
    # if repl is function, def func(matchobj): matchobj.group(1)
    # match.group(0) on "..(..)..", match.group(1) on (..)
    # if no () group in REexpr, then use: match.group(0)

    re.subn(pattern, repl, string, count=0, flags=0)
    # Perform the same operation as sub(),
    # but return a tuple (new_string, number_of_subs_made).
    REexp.sub(new_sub, string [,count=0])
    # count=0, means all
    # REexp = re.compile('(new1|new2|new3)')

    >>> p = re.compile('x*')
    >>> p.sub('-', 'abxd')
    '-a-b-d-'
    # how come???

    >>> p = re.compile('section{ ( [^}]* ) }', re.VERBOSE)
    >>> p.sub(r'subsection{\1}','section{First} section{second}')
    'subsection{First} subsection{second}'
    # () >> \1; groups stay the same as before

    >>> p = re.compile('section{ (?P [^}]* ) }', re.VERBOSE)
    >>> p.sub(r'subsection{\1}','section{First}')
    'subsection{First}'
    >>> p.sub(r'subsection{\g<1>}','section{First}')
    'subsection{First}'
    >>> p.sub(r'subsection{\g}','section{First}')
    'subsection{First}'
    # (?P..) >> \1, \g<1>, \g

    sub("(?i)b+", "x", "bbbb BBBB") returns 'x x'.
    # (?!) ignore case


    $$ String Translation

    * Use of Table module, named "maketrans"

    from string import maketrans # Required to call maketrans function.
    #
    intab = "aeiou"
    outtab = "12345"
    trantab = maketrans(intab, outtab) # (a-1, e-2, i-3, o-4, u-5)
    #
    str = "this is string example....wow!!!";
    print str.translate(trantab, 'xm');

    ReplyDelete
  5. prs22b -2

    $$ String Search

    RES = re.search("c", "abcde")
    # containing
    Return None if no position in the string matches the pattern;
    RES.groups()
    RES.gruoup(0)
    RES.group('NAME') for r"(?P)"
    REpattern.search(string[, pos[, endpos]])
    re.match("c", "abcde")
    # starting with
    LIST = re.split (REepr, STRING [, max])
    re.findall(r"RE", STRING)

    string.find(s, sub[, start[, end]]) # Return -1 on failure
    string.rfind(s, sub[, start[, end]]) # but find the highest index.
    string.index(s, sub[, start[, end]])
    # but raise ValueError when the substring is not found
    string.rindex(s, sub[, start[, end]])
    string.count(s, sub[, start[, end]])



    a = re.compile(r'''\d + # the integral part
    \. # the decimal point
    \d * # some fractional digits''', re.X)
    b = re.compile(r"\d+\.\d*")
    # re.X, re.VERBOSE : Whitespace within the pattern is ignored,
    except when in a character class or preceded by an unescaped backslash,
    and, when a line contains a '#'
    neither in a character class
    or preceded by an unescaped backslash,
    all characters from the leftmost such '#'
    through the end of the line are ignored.




    $$ Chinese Code

    # -*- coding: utf-8 -*-
    utf-8, big5, gbk, gb2312, cp936


    * decode
    text_gb2312.decode("gbk") # unncessary if system is in GB
    text_big5.decode("big5")
    text_utf.decode("utf9")

    str_gb2312.decode("gb2312").encode("utf-8")

    # TRADITIONAL : big5, big5hkscs, cp950
    # UNIFIED : gbk, gb18030,
    # SIMPLIFIED : gb2312, hz
    # JKC : iso2022_jp_2,
    # UNICODE : utf_7, utf_8, utf_16, utf_32;
    # UNICODE : utf_16_be, utf_16_le, utf_32_be, utf_32_le,


    * Windows system, set to Chinese - China; GB
    line.decode("gbk")

    10_28_Sermon_gb2312.txt
    10_28_Sermon_big5.txt
    10_28_Sermon_utf8.txt
    10_28_Sermon_utf16.txt

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. prs22b -3

    $$ File Arrangment

    documentation
    requires : toolDoc, p.helpT, p.lessonT [txt,hdg,pos]
    help2() : structure of project, files, classes, functions
    lesson2() : learning, language, built-in, features, tips

    each module
    invokes module toolDoc
    for documentation, to make help2(), lesson2()
    contains
    var : p (a dummy object),
    func : main(), help2(), lesson2(), initGlobal()

    each sub-module
    contains classes only,
    besides: main(), help2(), lesson2()
    class CLASS():
    def __init__(self, CALLERp):
    self.thisP = p;
    self.callerP = CALLERp
    # exec "self.callerP."+"FUNC()"
    # callerP: p.CLASSo.thisP.FUNC()

    file naming
    AAA999BB88 :
    AAA : project name

    999 : version serial, 2..8, excep 0/1/9
    9 extention, (1) 2..8, 922..988; (2) 2..8, 92..98;
    0 help/document;
    1/0 level separator, 2.3=213, or 203

    BB : sub-modules, b..w, except l/j/x/u/n/vowels
    x extention, b..w, xbb..xww
    j level separator, BjB, xbbxcc=bbjcc, or bb.cc
    u tool/utility, more common to other projects
    n notes, or nSUBname
    a/e/i/o/u//l/j (reserved)

    B sub-module, b..w, xbb..xww
    BB sub-sub-module, bc..bw, BB* bxcc..bxww
    BBB sub-sub-sub-module, BBB* bcd..bcw, bcxdd..bcxww
    B*B, xbbc..xbbw, B*B* xbbxcc..xbbxww

    99 : (reserved), temp for revisions, copies

    ReplyDelete
  8. prs42

    $$ Loading Chinese py file

    # from prs2ndu8 import *
    # prs2ndu8.py saved in utf-8
    # succeed, but require : str.decode("utf8")
    # add coding: utf-8 ; succeed in IMPORT; no need of decode()
    # from prs2ndu import *
    # prs2ndu.py saved in Unicode; fail in IMPORT
    # from prs2ndub import *
    # prs2ndu.py saved in Unicode big endian; fail in IMPORT
    # from prs2ndasc import *
    # prs2ndasc.py saved in ascii/ANSI endian; fail in IMPORT
    # add coding: cp936/gbk ; fail in IMPORT
    # add coding: utf-8 ; succeed in IMPORT



    $$ List

    pop([id]); remove(value);
    append(value); extend(list); insert(id, value);
    index(value); count(value); reverse(); sort();
    del list[:]/all; del [pos:stop]

    tuple
    a = (1,2), (3,4) >>> a == ((1,2), (3,4))
    a = 1, >>> a == (1,)
    a,b = (1,2) >>> a==1; b==2
    a,b = 1,2 >>> a==1; b==2
    (a,b) = (1,2) >>> a==1; b==2

    list("abc") >>> ["a","b","c"]
    tuple("abc") >>> ("a","b","c")

    ReplyDelete
  9. prs52

    $$ Class Oriented

    def __init__(self): pass
    # main() part, to use classObjName.var; this is more convenience
    # in __inti__, have to use self.var; this is more clas-oriented
    # def __new__(cls): pass # for inheritance of multi-generation, multi-parent
    # def __call__(self): pass # for mainCObj()
    # def __init__(self): pass # for post-instantiation of object


    $$ Loading Chinese py file

    # from prs2ndu8 import *
    # prs2ndu8.py saved in utf-8
    # succeed, but require : str.decode("utf8")
    # add coding: utf-8 ; succeed in IMPORT; no need of decode()
    # from prs2ndu import *
    # prs2ndu.py saved in Unicode; fail in IMPORT
    # from prs2ndub import *
    # prs2ndu.py saved in Unicode big endian; fail in IMPORT
    # from prs2ndasc import *
    # prs2ndasc.py saved in ascii/ANSI endian; fail in IMPORT
    # add coding: cp936/gbk ; fail in IMPORT
    # add coding: utf-8 ; succeed in IMPORT



    $$ List

    pop([id]); remove(value);
    append(value); extend(list); insert(id, value);
    index(value); count(value); reverse(); sort();
    del list[:]/all; del [pos:stop]

    tuple
    a = (1,2), (3,4) >>> a == ((1,2), (3,4))
    a = 1, >>> a == (1,)
    a,b = (1,2) >>> a==1; b==2
    a,b = 1,2 >>> a==1; b==2
    (a,b) = (1,2) >>> a==1; b==2

    list("abc") >>> ["a","b","c"]
    tuple("abc") >>> ("a","b","c")

    """
    # END of LESSON text string

    ReplyDelete
  10. toolDoc2

    $$ File arrangement

    Each module contains:
    class dummy(): pass
    p = dummy()
    def main()
    def initGlobal() # prepare the dummy "p"
    p.i6c = toolDoc2.info6C(p) # give the reference "p"
    p.helpT=[""] # structure of files/modules, classes, functions,
    p.lessonT=[""] # learning of language, built-in,

    Mainly, "p" handles all global var, including external var
    * Related variables and functions are grouped
    into a class or module, as properties and methods
    * var inside func is local, temporary until func is done
    * var inside class is static, active until object is deleted
    * var inside a module/file is static, no other modules can access
    unless from MOD import *
    unless invoke by SUBmodule.var
    * Only the object var (as reference) is able to cross the scopes


    ReplyDelete
  11. __init__

    $$ Notes - arguments

    func (farg, *args)
    func (1, 2, 3) == farg=1, args=[2,3]
    func (farg, **kwargs)
    func (f=1, a1=2, a2=3) == farg=1, kwarg={"a1":2,"a2"=3}

    # in RE module, result.start(i) == result.group(i+1).posINoriginal
    # y[yy.start():yy.end()]==yy for yy in re.find(REepr, y, FLAGS)
    # yy.start() == yy.start(0) for yy.group(1)

    # find all headings; re.M a flag of multi-line

    ReplyDelete
  12. dict21

    $$ Chinese internal code

    # -*- coding: utf-8 -*-
    # cp936, gb2312 (, GBK、GB18030), utf8, utf16, big5

    # LIST = STRING.split (SEPARATOR, MAXsplits)
    # re.split (REexp, STRING)
    # LIST = re.split ("sep|sep", STRING)
    # SEPARATOR.join (SEQUENCE)
    # Big-5 ok:
    # if line = FILE.readline()
    # if "".join(line.split(","))
    # if "".join(line.split(",")[2])
    # ecd_21b_tw2.csv : unicode(line, "big5")
    # line.split()[2].decode("big5") = u"xxx"
    # unicode(line, "big5") = u"xxx"
    # line.decode("big5") = u"xxx"
    # line.index (SUBstringCHINESE)


    $$ Functions to use files.

    f.open ("path/filename","type")
    The first argument is a string containing the filename.
    The second argument is another string containing a few characters
    describing the way in which the file will be used.

    mode can be 'r' when the file will only be read,
    'w' for only writing (an existing file with the same name will be erased),
    and 'a' opens the file for appending;
    any data written to the file is automatically added to the end.
    'r+' opens the file for both reading and writing. The mode argument is optional;
    'r' will be assumed if it’s omitted.

    On Windows, 'b' appended to the mode opens the file in binary mode,
    so there are also modes like 'rb', 'wb', and 'r+b'.

    f.read()
    # 'This is the entire file.\n'
    f.readline()
    # read one line at a time;
    # then 'Second line of the file\n'

    f.readlines (intByte)
    the same as read(), but parse into lines;
    If given an optional parameter intByte, it reads that many bytes from the file and enough more to complete a line,
    f.xreadlines()
    # the same as readlines() to read the entire file,
    # readlines() returns a list, xreadlines returns a iterator

    for line in f
    the best way to read a line;
    range() returns an iterator object;
    iterator, a generator-like tuple, one same space for all elements, next() required

    ReplyDelete
  13. dict22

    $$ Import Module

    import MOD2 [as M1], MOD3 [as M2]
    from MOD import IDENTIFIER [as ID2], IDEN [as ID3]
    from MOD import (IDENTIFIER [as ID2], IDEN [as ID3])
    from [PAK.]PACKAGE import MOD
    from MOD import * # import all identifiers

    import sys
    del sys.modules ["MYmodule"] # no way, Python does not support
    del MYmodule
    reload (MYmodule)
    imp.reload (MYmodule) # in Python 3
    setattr(package, "MYmodule", None)



    $$ Chinese internal code

    # -*- coding: utf-8 -*-
    # cp936, gb2312 (, GBK、GB18030), utf8, utf16, big5

    # LIST = STRING.split (SEPARATOR, MAXsplits)
    # re.split (REexp, STRING)
    # LIST = re.split ("sep|sep", STRING)
    # SEPARATOR.join (SEQUENCE)
    # Big-5 ok:
    # if line = FILE.readline()
    # if "".join(line.split(","))
    # if "".join(line.split(",")[2])
    # ecd_21b_tw2.csv : unicode(line, "big5")
    # line.split()[2].decode("big5") = u"xxx"
    # unicode(line, "big5") = u"xxx"
    # line.decode("big5") = u"xxx"
    # line.index (SUBstringCHINESE)


    $$ Functions to use files.

    f.open ("path/filename","type")
    The first argument is a string containing the filename.
    The second argument is another string containing a few characters
    describing the way in which the file will be used.

    mode can be 'r' when the file will only be read,
    'w' for only writing (an existing file with the same name will be erased),
    and 'a' opens the file for appending;
    any data written to the file is automatically added to the end.
    'r+' opens the file for both reading and writing. The mode argument is optional;
    'r' will be assumed if it’s omitted.

    On Windows, 'b' appended to the mode opens the file in binary mode,
    so there are also modes like 'rb', 'wb', and 'r+b'.

    f.read()
    # 'This is the entire file.\n'
    f.readline()
    # read one line at a time;
    # then 'Second line of the file\n'

    f.readlines (intByte)
    the same as read(), but parse into lines;
    If given an optional parameter intByte, it reads that many bytes from the file and enough more to complete a line,
    f.xreadlines()
    # the same as readlines() to read the entire file,
    # readlines() returns a list, xreadlines returns a iterator

    for line in f
    the best way to read a line;
    range() returns an iterator object;
    iterator, a generator-like tuple, one same space for all elements, next() required

    ReplyDelete
  14. dict23n -1

    $$ Exception Handling

    try:
    operation_that_can_throw_ioerror()
    except IOError:
    handle_the_exception_somehow()
    else:
    # we don't want to catch the IOError if it's raised
    another_operation_that_can_throw_ioerror()
    finally:
    something_we_always_need_to_do()


    try:
    You do your operations here;
    except ExceptionI:
    If there is ExceptionI, then execute this block.
    except ExceptionII:
    If there is ExceptionII, then execute this block.
    else:
    If there is no exception then execute this block.

    try:
    You do your operations here;
    except:
    If there is any exception, then execute this block.

    try:
    You do your operations here;
    except Exception1, Exception2:
    If there is any from the exception list, then execute this block.

    try:
    You do your operations here;
    finally:
    This would always be executed,
    whether the try-block raised an exception or not.


    except ValueError, Argument_detail:
    print "The argument does not contain numbers\n", Argument_detail
    except (RuntimeError, TypeError, NameError):
    except IOError, (errno, strerror):
    print "I/O error(%s): %s" % (errno, strerror)

    # raise [Exception [, args [, traceback]]]
    try:
    Business Logic here...
    if level < 1:
    raise "Invalid level!", level
    except "Invalid level!":
    Exception handling here...

    >>> try:
    ... raise Exception('spam', 'eggs')
    ... except Exception, inst:
    ... print type(inst) # the exception instance
    ... print inst.args # ('spam', 'eggs'), arguments stored in .args
    ... print inst # ('spam', 'eggs'), __str__ allows args to
    # printed directly
    ... x, y = inst # __getitem__ allows args
    # to be unpacked directly



    $$ Print statement

    # Formatting
    print string.rjust(`x*x*x`, 4)
    print '%2d %3d %4d' % (x, x*x, x*x*x)
    string.zfill('12', 5)
    print "".join(list2)
    print('h', end='') # Python 3
    print('a', 'b', 'c', sep='') # Python 3
    print repr(x).rjust(2)
    print '%-10s ==> %10d' % (name, phone)
    # %-10s spaces at left
    table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
    print '%(Jack)d; %(Sjoerd)d; %(Dcab)d' % table
    # works with dictionary



    class WritableObject:
    def __init__(self):
    self.content = []
    def write(self, string):
    self.content.append(string)

    # example with redirection of sys.stdout
    foo = WritableObject() # a writable object
    sys.stdout = foo # redirection
    print "one, two, three, four" # some writing
    print "little hat"
    print "little hat"
    sys.stdout = sys.__stdout__ # remember to reset sys.stdout!
    print "foo's content:", foo.content # show the result of the writing

    # example with redirection of the print statement
    bar = WritableObject() # another writable object
    print >>bar, "one, two, three, four" # some (redirected) writing
    print >>bar, "little hat made of paper"
    print "bar's content:", bar.content # the result

    ReplyDelete
  15. dict23n -2

    $$ SQL SQLite3


    import sqlite3
    >>> sqlite3.version # the version of the pysqlite
    >>> sqlite3.sqlite_version # the version of the SQLite database library

    sqlite> .tables # a list of tables in the test.db database
    sqlite> .exit # terminates the interactive session of the sqlite3 command line tool.

    data3 = str(input('Please enter name: '))
    query = "DELETE FROM Zoznam WHERE Name = '%s';" % data3.strip()
    mydata = c.execute(query)

    # Open a database
    conn = sqlite3.connect('dict.db') # open a database
    conn = sqlite3.connect(':memory:')
    # Create a table
    CREATE TABLE tab2 (col3 TEXT, col4 INT, col5 TEXT)
    CREATE TABLE Friends(Id INTEGER PRIMARY KEY, Name TEXT);
    CREATE TABLE Images(Id INTEGER PRIMARY KEY, Data BLOB);
    # Insert a record
    INSERT INTO Cars VALUES (1,'Audi',52642)
    INSERT INTO Cars (Price) VALUES (52642)
    # Update a record
    UPDATE tab2 SET col3 = 'John Doe' WHERE col3 = 'Andy Hunter'
    # Delete a record
    DELETE FROM tab2 WHERE col3 = 'John Doe'
    # Delete a table
    DROP TABLE IF EXISTS tab1


    sql = "SELECT * FROM albums WHERE artist=?"
    c.execute(sql, [("Red")])
    # c.execute("SELECT * FROM albums WHERE artist=?", [("Red")])
    c.fetchall()

    c.fetchone()
    while True:
    row = c.fetchone()
    if row == None: break
    print row[0], row[1], row[2]

    with con:
    con.row_factory = lite.Row
    # list into dictionary with field names as keys
    ...
    rows = cur.fetchall()
    for row in rows:
    print "%s %s %s" % (row["COL2"], row["COL3"], row["COL4"])

    for row in cursor.execute("SELECT rowid, * FROM albums ORDER BY artist"):
    print row

    conn.row_factory = sqlite3.Row
    # Row objects that are kind of like Python dictionaries
    # and give you access to the row’s fields just like a dictionary.


    # Insert image
    fin = open("woman.jpg", "rb")
    img = fin.read()
    data = img
    binary = sqlite3.Binary(data)
    cur.execute("INSERT INTO Images(Data) VALUES (?)", (binary,) )

    # Read image
    cur.execute("SELECT Data FROM Images LIMIT 1")
    data = cur.fetchone()[0]
    fout = open('woman2.jpg','wb')
    fout.write(data)

    # Metadate
    cur.execute('PRAGMA table_info(Cars)')
    data = cur.fetchall()
    for d in data:
    print d[0], d[1], d[2]
    === 0 Id INT

    cur.execute('SELECT * FROM Cars')
    col_names = [cn[0] for cn in cur.description]

    cur.execute("SELECT name FROM sqlite_master WHERE type='table'")
    rows = cur.fetchall()
    for row in rows:
    print row[0]




    # execute()

    c.execute('SELECT * FROM engchi')
    c.execute("SELECT * FROM albums WHERE artist=?", [("Red")])
    # works wuith "?" and second arg (list of tuples)
    c.execute("UPDATE Cars SET Price=? WHERE Id=?", (uPrice, uId))
    cur.execute("SELECT Name, Price FROM Cars WHERE Id=:Id", {"Id": uId})
    # :KEY -- dictionry {"KEY": uValue}

    c.executescript('SELECT * FROM engchi;')
    # executescript issues COMMIT
    # commands end with ";"
    c.executemany (INSERT INTO engchi (type, word) VALUES (?,?)', ss0s)
    # if ssOs = [(1,1), (2,2), (3,3)]

    ReplyDelete
  16. dict23n -3

    $$ Import Module

    import MOD2 [as M1], MOD3 [as M2]
    from MOD import IDENTIFIER [as ID2], IDEN [as ID3]
    from MOD import (IDENTIFIER [as ID2], IDEN [as ID3])
    from [PAK.]PACKAGE import MOD
    from MOD import * # import all identifiers

    import sys
    del sys.modules ["MYmodule"] # no way, Python does not support
    del MYmodule
    reload (MYmodule)
    imp.reload (MYmodule) # in Python 3
    setattr(package, "MYmodule", None)



    $$ Chinese internal code

    # -*- coding: utf-8 -*-

    # -*- coding: utf-8 -*-
    # cp936, gb2312 (, GBK、GB18030), utf8, utf16, big5

    # LIST = STRING.split (SEPARATOR, MAXsplits)
    # re.split (REexp, STRING)
    # LIST = re.split ("sep|sep", STRING)
    # SEPARATOR.join (SEQUENCE)
    # Big-5 ok:
    # if line = FILE.readline()
    # if "".join(line.split(","))
    # if "".join(line.split(",")[2])
    # ecd_21b_tw2.csv : unicode(line, "big5")
    # line.split()[2].decode("big5") = u"xxx"
    # unicode(line, "big5") = u"xxx"
    # line.decode("big5") = u"xxx"
    # line.index (SUBstringCHINESE)


    $$ Functions to use files.

    f.open ("path/filename","type")
    The first argument is a string containing the filename.
    The second argument is another string containing a few characters
    describing the way in which the file will be used.

    mode can be 'r' when the file will only be read,
    'w' for only writing (an existing file with the same name will be erased),
    and 'a' opens the file for appending;
    any data written to the file is automatically added to the end.
    'r+' opens the file for both reading and writing. The mode argument is optional;
    'r' will be assumed if it’s omitted.

    On Windows, 'b' appended to the mode opens the file in binary mode,
    so there are also modes like 'rb', 'wb', and 'r+b'.

    f.read()
    # 'This is the entire file.\n'
    f.readline()
    # read one line at a time;
    # then 'Second line of the file\n'

    f.readlines (intByte)
    the same as read(), but parse into lines;
    If given an optional parameter intByte, it reads that many bytes from the file and enough more to complete a line,
    f.xreadlines()
    # the same as readlines() to read the entire file,
    # readlines() returns a list, xreadlines returns a iterator

    for line in f
    the best way to read a line;
    range() returns an iterator object;
    iterator, a generator-like tuple, one same space for all elements, next() required

    ReplyDelete
  17. dict24

    $$ Chinese Inner Code

    ll = line.decode("gbk")
    # decode into u"xxxx"
    # Windows system is set for Chinese-China
    # py file is set to coding CP936 - GBK
    p.rows[30][1].index("bac")
    p.rows[30][2].index("院長".decode("gbk"))

    ReplyDelete
  18. mg22

    x=[]; temp2=[x.extend(list(db2[y][3:9])) for y in range(len(db2))]
    [db2[x][y] for x in range(len(db2)) for y in range(3,9) ]
    # two ways, To get all numbers into one-level list

    x=[db2[y][3] for y into range(len(db2))]
    # To get all 3rd numbers in one-level list

    for x,y,z in ((1,2,3),(4,5,6)): print x,y,z
    for x,(y,z) in [(1,(2,3)),(4,(5,6))]: print x,y,z;
    # multiple variables in FOR statement

    print "%6.4f" % (1.0*st.count(st[0])/len(st))
    # calculate the percentage of a number
    map(lambda x: 1.0*st.count(x)/len(st), [db2[0][y] for y in range(3,9)])
    # list of percentage for a row of numbers

    iter(SEQUENCE)
    # sequence: list, tuple, string;
    # generate an iterator object, (S[0], S[1], ...)
    enumerate(LIST)
    # generate an iterator object, ((0, L[0]), (1, L[1]), ...)

    ITERABLES, must work with IT.next() to get next element;
    if sequence changed before next(), then iter() changed as well;

    ReplyDelete
  19. mg23 -1

    $$ A. List Comprehesion

    x=[]; temp2=[x.extend(list(db2[y][3:9])) for y in range(len(db2))]
    [db2[x][y] for x in range(len(db2)) for y in range(3,9) ]
    # two ways, To get all numbers into one-level list

    x=[db2[y][3] for y into range(len(db2))]
    # To get all 3rd numbers in one-level list

    for x,y,z in ((1,2,3),(4,5,6)): print x,y,z
    for x,(y,z) in [(1,(2,3)),(4,(5,6))]: print x,y,z;
    # multiple variables in FOR statement

    print "%6.4f" % (1.0*st.count(st[0])/len(st))
    # calculate the percentage of a number
    map(lambda x: 1.0*st.count(x)/len(st), [db2[0][y] for y in range(3,9)])
    # list of percentage for a row of numbers


    $$ B. Iteraables

    iter(SEQUENCE)
    # sequence: list, tuple, string;
    # generate an iterator object, (S[0], S[1], ...)
    enumerate(LIST)
    # generate an iterator object, ((0, L[0]), (1, L[1]), ...)

    ITERABLES, must work with IT.next() to get next element;
    if sequence changed before next(), then iter() changed as well;

    reduce(f(x,y), [1, 2, 3, 4]) # f(f(f(1,2),3),4)
    reduce(f(x,y), [1, 2, 3, 4], 9) # f(f(f(f(9,1),2),3),4)
    map(f(x), [1, 2, 3, 4, 5]) # [f(1), f(2), f(3)]; map(func,iterable)
    zip("1,2,3",”a", "b") # ("1a", "2b"); zip(iterable, ...)

    ReplyDelete
  20. mg23 -2

    $$ C. String Formatting

    str(OBJ/NUM/STRING/SEQUENCE) # return a string
    repr(x) # return a string for interpretation
    # replaced into repr MODULE
    # Python3 rename to reprlib MODULE
    STRING.rjust()
    STRING.center()
    STRING.ljust()
    STRING.zfill(NUM) # fill zero

    STRING.format(value1, value2,...) # work with {}
    'The value of PI is approximately {}.'.format(math.pi)
    '{0} and {1}'.format('spam', 'eggs') # with ordered values
    'This {food} is {adjective}.'.format(\
    food='spam', adjective='absolutely horrible') # with named values
    'The story of {0}, {1}, and {other}.'.\
    format('Bill', 'Manfred', other='Georg') # with mixed
    'PI is {!r}.'.format(math.pi) # apply repr()
    'PI is {!s}.'.format(math.pi) # apply str()
    'PI is {0:.3f}.'.format(math.pi) # convert to float with 3 decimals
    'PI is {0:10d}.'.format(math.pi) # convert to integer with 10 digits long

    table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
    print ('Jack: {0[Jack]:d}; Sjoerd: \
    {0[Sjoerd]:d}; Dcab: {0[Dcab]:d}'.format(table)) # with DICTIONARY
    coord = (3, 5)
    print 'X: {0[0]}; Y: {0[1]}'.format(coord) # with LIST

    '{:<30}'.format('left aligned') # with length of 30 characters
    '{:>30}'.format('right aligned')
    '{:^30}'.format('centered')
    '{:*^30}'.format('centered') # use '*' as a fill char

    '{:+f}; {:+f}'.format(3.14, -3.14) # show PLUS and MINUS
    '{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers
    '{:-f}; {:-f}'.format(3.14, -3.14) # show only the MINUS -- same as '{:f}; {:f}'

    >>> '{:,}'.format(1234567890) # add thousand separator
    >>> 'Correct answers: {:.2%}'.format(19.5/22) # percentage
    >>> import datetime
    >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
    >>> '{:%Y-%m-%d %H:%M:%S}'.format(d) # with date MODULE

    for align, text in zip('<^>', ['left', 'center', 'right']):\
    '{0:{fillx}{alignx}16}'.format(text, fillx=align, alignx=align) # nested
    >>> octets = [192, 168, 0, 1]
    >>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets) # convert to octets
    'C0A80001'

    >>> from string import Template
    >>> s = Template('$who likes $what')
    >>> s.substitute(who='tim', what='kung pao')
    'tim likes kung pao'

    ReplyDelete
  21. mg23 -3

    $$ E. Input and Output

    s = raw_input('--> ')
    print s

    >>> f.write('This is a test\n')

    >>> f.read() # read the whole file
    >>> f.readline() # read one line
    >>> f.readlines() # read the whole file, and split into lines
    ['This is the first line of the file.\n', 'Second line of the file\n']

    >>> f = open('/tmp/workfile', 'w')
    >>> print f




    $$ F. File Functions

    FILE.open (FILEname, FILEtype)
    # file name can include PATH
    # file type: "w", "r", "a"/append, "+r"/both
    FILE.close()
    FILE.name # file name
    FILE.fileno # integer file id in OS
    FILE.next() # next line
    FILE.tell () # current position, in byte order
    FILE.seek (OFFset, /FROM/) # from: 0/begin of file, 1/current, 0/eof of file
    FILE.read (/NUMbytes/)
    FILE.readline (/NUMbytes/)
    FILE.readlines (/NUMbytes/)
    FILE.write (STRING)
    FILE.writelines (SEQUENCE)


    $$ G. String Functions

    STRING.strip(/'CHARstringTOdelet'/)
    # delete chars from beginning and ending until non desired
    # deafult is to delete whitespace
    STRING.lstrip(/'CHARstringTOdelet'/) # delete from beginning
    STRING.rstrip(/'CHARstringTOdelet'/) # delete from ending

    STRING.split (/DELIMETERstring/,/ISaddLINEfeed/) # return a list
    STRING.splitlines (/ISappendLINEfeed/)
    STIRNGconnector.join (SEQUENCE)

    from string import maketrans
    intab = "aeiou"
    outtab = "12345"
    trantab = maketrans(intab, outtab) # a>>1, e>>2,...
    str = "this is string example....wow!!!";
    print str.translate(trantab, /CHARstringTOdelete/);

    ReplyDelete
  22. mg23 -4

    $$ H. Regular Expression

    >>> import re
    >>> m = re.search('(?<=abc)def', 'abcdef') # (?<=xx)yy if yy preceded by xx
    >>> m.group(0)
    'def'

    >>> m = re.search('(?<=-)\w+', 'spam-egg')
    >>> m.group(0)
    'egg'

    prog = re.compile(pattern) # compile to re object
    result = prog.match(string)

    result = re.match(pattern, string)

    re.I, re.IGNORECASE; re.M, re.MULTILINE;
    re.compile(pattern, flags=0)
    re.search(pattern, string, flags=0)
    re.match(pattern, string, flags=0)
    re.split(pattern, string, maxsplit=0, flags=0)
    str=re.sub(pattern, repl, string, count=0, flags=0) # replace
    tuple=re.subn(pattern, repl, string, count=0, flags=0) # (str3, numREPL)

    >>> re.split('\W+', 'Words, words, words.')
    ['Words', 'words', 'words', '']
    >>> re.split('(\W+)', 'Words, words, words.')
    ['Words', ', ', 'words', ', ', 'words', '.', '']
    >>> re.split('\W+', 'Words, words, words.', 1)
    ['Words', 'words, words.']
    >>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
    ['0', '3', '9']

    search(string[, pos[, endpos]])
    match(string[, pos[, endpos]])
    split(string, maxsplit=0)
    findall(string[, pos[, endpos]])
    finditer(string[, pos[, endpos]])
    sub(repl, string, count=0)
    subn(repl, string, count=0)

    >>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
    >>> m.group(0) # The entire match
    'Isaac Newton'
    >>> m.group(1) # The first parenthesized subgroup.
    'Isaac'
    >>> m.group(2) # The second parenthesized subgroup.
    'Newton'
    >>> m.group(1, 2) # Multiple arguments give us a tuple.
    ('Isaac', 'Newton')

    >>> m = re.match(r"(?P\w+) (?P\w+)", "Malcolm Reynolds")
    >>> m.group('first_name')
    'Malcolm'
    >>> m.group('last_name')
    'Reynolds'
    >>> m.group(1)
    'Malcolm'
    >>> m.group(2)
    'Reynolds'

    >>> m = re.match(r"(..)+", "a1b2c3") # Matches 3 times.
    >>> m.group(1) # Returns only the last match.
    'c3'

    >>> m = re.match(r"(\d+)\.(\d+)", "24.1632")
    >>> m.groups()
    ('24', '1632')


    $$ J. Regular Expression in JavaScript

    * Javascript

    # \.X \b boudary, \B non boundary;
    # \w [A-Za-z0-9_], \W non letter; \d digit [0-9], \D non digit;
    # \s whitespace, \S non whitespace;
    # \. ., \" ", \$, \^;
    # \n line feed, \r c return; \t h-tab, \v v-tab; \f form feed;
    # \cX eg. \cM control-M; \0 NULL;
    # \.xHH, \uHHHH hex code;

    pos ^ beginning, ^a; $ ending, z$
    num a* 0 or more 'a's; a+ 1 or more 'a's; a? 0 or 1 'a';
    . one of any digit or char
    (xx) match xx and store to groups
    (?=x) match but not store
    x(?=y) match aslo if followed by y
    x(?!y) match also if not followed by y

    x|y x or y
    {n} a{2} 2 a's, aa; a{1,3} a, aa, aaa;
    [x] [xyz] x or y or z; [^xyz] no x or y or z; [abcd] == [a-d]
    [\b] backspace

    exec() re=/d(b)/g; list=re.exec(str);; list=/d(b)/g.exec(str);
    # list, list.index, list.input, list[0] /macthed substr
    # list[1], list[2]... stored 1, 2...
    # re.lastIndex, re.source /re string;
    # re.ignoreCase, re.global / all-repeat, re.multiline;
    test() re.test(subSTR)
    match() list=str.match(regEXP);
    search() int=str.search(regEXP);
    replace() str3=str2.replace(/(\w+)\s(\w+)/, "$2, $1") # with (xx)'s
    # str3=str2.replace(substr,newsub, flgs)
    split() list=str.split(separator, /numlist/)

    ReplyDelete
  23. mg24

    # __repr__ returns a string to execute
    # __str__ works in PRINT statement

    # inside class, only methods, def func(self, [args])
    # inside method, call by self.property and self.method

    ReplyDelete
  24. mg25

    mk1-p, sk2-p; mt3-p; sk1-p, sk3-p, st1-p, st3-p

    EXEC statement, exec COMMANDstring may return a value
    EVAL function, eval (EXPRESSIONstring) must return a value
    COMPILE function, compile (COMMANDstring, "", EXECfunc)
    compile(source, filename, mode[, flags[, dont_inherit]])
    EXPR function,
    returns a COMMANDstring for eval(expr(object))
    works with __repr__ in class

    # exec STATEMENTstring
    # eval EXPstring
    # map (FUNC, ARG2list, ARG3list)


    # __repr__ returns a string to execute
    # __str__ works in PRINT statement

    # inside class, only methods, def func(self, [args])
    # inside method, call by self.property and self.method

    a += b - c :: a = a + (b - c)
    [x /if switch(x) else xx/ for x in items /if filter(x)/]

    ReplyDelete
  25. mg24h

    $$ List of Methods : All

    import toolDoc

    CLASS dummy()
    p = dummy() # global var
    DEF main()
    DEF help2() # this function
    DEF lesson2() # learned during coding
    DEF initGlobal()



    $$ Tip : Global variable through dummy class

    class dummy():

    # PURPOSE : to create an object to carry values among classes or functions

    # REASON : in class/function, cannot reach global simple variables (number, string)
    # USAGE : x=dummy(); x.a=2; del x.a; # add/remove a properties
    pass

    p = dummy()
    # global passing channel

    ReplyDelete