#Chapter10:Batteries included
# Question :regular expression
#1 simple example about module
import sys
sys.path.append('E:\pycode')
import hello #excute hello.py and a new file appears (hello.pyc)
import hello #nothing happen,they mean define things not to do things,so just need define once
hello = reload(hello)#show message again ;python 3.0 remove,can use exec,better stay away from it
import p10_m1,p10_m2
#2 define a func in a module
p10_m1.f1()
#label_1---------------
# ---this is module1---
# func name is p10_m1
# ---this is module2---
# p10_m1 : f1()
#3 makeing your modules available
# --3.1-- put your module in the right place
# all sys.path or your appending path
import sys,pprint
pprint.pprint(sys.path)
['E:\pycode','E:\pycode1'] # Question
print(sys.path) # pprint is more intelligent than print
# --3.2-- Telling the Interpreter Where to Look
# -- sys.path.append('E:\pycode')
# -- ENVIRONMENT VARIABLES
#4 naming your module .pyw # Question
#5 packages
# --5.1 import--
print '------------'
import p10_package
print dir()#当前模块中定义的名称列表
from p10_package import*
print PI # __init__
print dir(p10_package)
print '__name__',p10_package.__name__
print '__path__',p10_package.__path__
print '__package__',p10_package.__package__
print '__file__',p10_package.__file__
import p10_package.m1
print p10_package.m1.PI
print dir(p10_package.m1)
print '__name__',p10_package.m1.__name__
print '__package__',p10_package.m1.__package__
print '__file__',p10_package.m1.__file__
from p10_package import m2
print m2.PI
# --5.2 dir(module)--
# --5.3 moudule.__name__ etc--
# --5.4 help--
help(p10_package.m1) # show all about m1
help(p10_package) # show all about __init__, and package content name (m1,m2)
#6 documentation
print '------------'
print range.__doc__
print p10_package.__doc__ #None
#7 the standard library
print '------------'
# --7.1 sys--
# Question : where can I find all reference and the usage of these
# http://python.org/doc/lib/types-set.html
# The sys module gives you access to variables and functions that are closely linked to the Python interpreter.
import sys
print sys.argv #['E:/pycode/p10.py']
try:
pass
except:
exit(['byebye'])
sys.modules # all of python personal module,so many
sys.path
print sys.platform # win32
#print dir(sys.stdin) #input
#print dir(sys.stdout)
#print dir(sys.stderr)
# --7.2 OS--
print '------------'
# The os module gives you access to several operating system services
import os
os.environ # Mapping with environment variables
#os.system('D:\Python27\python.exe') # excute something in subshell,similiar with "execv"
print os.sep # \ ; Separator used in paths,
print os.pathsep # ; Separator to separate paths
print os.linesep # Line separator ('\n', '\r', or '\r\n')
print os.urandom(2) # Returns n bytes of cryptographically(加密) strong random data
import webbrowser
# webbrowser.open('http://www.baidu.com') #open web url,?just pop up web
# --7.3 fileinput--
#Question: the usage
print '------------'
import fileinput
fileinput.input() # Question ?
print 'filename = ',fileinput.filename()
print 'lineno = ',fileinput.lineno()
print 'isfirstline() = ',fileinput.isfirstline()
print 'isstdin() = ',fileinput.isstdin()
print 'nextfile() = ',fileinput.nextfile()
print 'close() = ',fileinput.close()
# --7.4 Sets,Heaps,and Deques--
# -- set --
print set(range(3)) #set([0, 1, 2])
print set(['fee','fie,','foe']) #set(['foe', 'fee', 'fie,'])
a = set([1,2,3])
b = set([2,3,4])
print a.union(b) # set([1, 2, 3, 4])
print a|b
c = a&b
print c #set([2, 3])
print a.intersection(b) # set([2, 3])
print c.issubset(a) #True
print c <= a #True
print a.issuperset(c)#True
print a.difference(b) #set([1])
print a-b #set([1])
print a.symmetric_difference(b) #set([1, 4])
print a^b
print a.copy() #set([1, 2, 3])
print a.copy() is a #False
#Question:reduce?
mySet = []
for i in range(5):
mySet.append(set(range(i,i+5)))
print mySet
#[set([0, 1, 2, 3, 4]), set([1, 2, 3, 4, 5]), set([2, 3, 4, 5, 6]), set([3, 4, 5, 6, 7]), set([8, 4, 5, 6, 7])]
print reduce(set.union,mySet)
#set([0, 1, 2, 3, 4, 5, 6, 7, 8])
# sets are mutable
a = set([1])
b = set([2])
# a.add(b) wrong
a.add(frozenset(b))
print a #set([1, frozenset([2])])
# -- Heaps --
# Question : heapify
from heapq import *
heap = []
for n in range(5):
heappush(heap,n)
print heap
print heappop(heap) #Pops off the smallest element in the heap
print heapify(heap) #None ,Enforces the heap property on an arbitrary list
print heapreplace(heap,8),heap #1 [2, 3, 8, 4];pop off the smallest ,and replace
print nlargest(2,heap),heap #[8, 4] [2, 3, 8, 4]
print nsmallest(2,heap),heap #[2, 3] [2, 3, 8, 4]
from random import shuffle
data = range(10)
shuffle(data)
print data #[5, 9, 7, 0, 1, 4, 8, 6, 3, 2]
# -- Deques --
from collections import deque
q = deque(range(5))
q.append(5)
q.appendleft(6)
print q #deque([6, 0, 1, 2, 3, 4, 5])
print q.pop() #5
print q.popleft() #6
print q #deque([0, 1, 2, 3, 4])
q.rotate(3) # show location
print q #deque([2, 3, 4, 0, 1])
q.rotate(-2)
print q #deque([4, 0, 1, 2, 3])
# --7.5 time--
# home
# --7.6 random--
from random import *
print '--random()',random() # 0=<n<=1
print 'getrandbits(2) ',getrandbits(2) # 0=<n<(11二进制)
print 'uniform(3,10) ',uniform(3,10) # between 3~ 10,float
print 'randrange(1,10,2)',randrange(1,10,2) # 1~10 ,step 2,1,3,5,7,9
print 'choice([1,4,6,7])',choice([1,4,6,7]) # choice(seq),1,4,6,7
s = [1,2,3]
shuffle(s) # shuffle seq random
print 'shuffle s= ',s
print 'sample(seq,n)',sample(s,2) # choise n elements from seq random
# --7.7 shelve--
import shelve
s = shelve.open('test.bat')
s['x']=['a','b'] #similar with dictionary,but key must be string
s['x']=['c']
s['x'].append('d')
print s['x'] #just c; for 'd' was appended to the copy
temp = s['x']
temp.append('e')
s['x']=temp
print s['x'] #['c', 'e']
s.writeback = True
s['x'].append('f')
print s['x'] #['c', 'e', 'f']
s.writeback = False # no affect
s['x'].append('g')
print s['x'] #['c', 'e', 'f', 'g'],if don't write anymore,must close
s.close()
#s['x'].append('g')
#print s['x']
#--a simple database example
import sys,shelve
def store_person(db):
pid = raw_input('enter unique ID number')
person = {}
person['name']=raw_input('enter name:')
person['age']=raw_input('enter age:')
person['phone']=raw_input('enter phone:')
db[pid] = person
print '-----------'
print db
def lookup_person(db):
pid=raw_input('enter id number:')
field = raw_input('what would u like to know?(name,age,phoe)')
field = field.strip().lower()
print field.capitalize()+':',db[pid][field]
def print_help():
print 'the availabel commands are:'
print 'store :stores information about a person'
print 'lookup:look up a person from ID number'
print 'quit :save changes and exit'
print '? :print these message'
def enter_command():
cmd = raw_input('enter command(? for help):')
cmd = cmd.strip().lower()
return cmd
def main():
database = shelve.open('p10_database.dat')
try:
while True:
cmd = enter_command()
if cmd=='store':
store_person(database)
elif cmd=='lookup':
lookup_person(database)
elif cmd=='?':
print_help()
elif cmd=='quit':
return
finally:
database.close()
#if __name__=='__main__':main()
#8 re (regular expression)
#http://wiki.ubuntu.org.cn/Python正则表达式操作指南
# --8.1 the wildcard-- 通配符
# .ython (python,wython...) dot matchs any character except a newline
# --8.2 Escaping Special Characters -- 转义特殊字符
# 'python\\.org' & python.org (avoid . be thought to be the wildcard)
# --8.3 character sets--
# [pj]ython = python | jython
# [a-zA-Z0-9]
# [^adc] match any character except a,b,c
# --8.4 alternatives and subpatterns (pipe)
# 'python|perl'
# 'p(ython|erl)'
# -8.5 optional and repeated subpatterns
# (pattern)* :pattern is repeated zero or more times
# (pattern)+ :one or more times
# (pattern){m,n} :from m to n times
# r'(http://)?(www\.)?python\.org'
# http://www.python.org
# www.python.org
# http://python.org
# python.org
# --8.6 the beginning and end of a string
# 'w+' & ... www.python.org
# the beginning:'^ht+p' & ... 'http://python.org' 'htttttp://python.org' ;not 'www.http.org'
# the end: $
# --8.7 contents of the re module
# Question: findall()
import re
# compile
p = re.compile('ab*')
print p
#match()
m = p.match('ab')
print m.group() #return re 匹配的字符串
print m.start() #0 返回匹配开始的位置
print m.end() #2
print m.span() #(0,2)
#findall() 返回一个匹配字符串行表
p = re.compile('\d+')
m = p.match('0123456789')
print m.group()
print p.findall('12 frumers frumming,11pipers piping,10lords a-leaping')
print re.search('\d','4')