http://blog.csdn.net/ly21st http://ly21st.blog.chinaunix.net
分类: Python/Ruby
2011-10-04 18:55:28
包
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
模块中有什么使用dir
>>> import copy
>>> [n for n in dir(copy) if not n.startswith('_')]
['Error', 'PyStringMap', 'copy', 'deepcopy', 'dispatch_table', 'error', 'name', 't', 'weakref']
+++++++++++++++++++++++++++++++++++++++++++
__all__变量
>>> copy.__all__
['Error', 'copy', 'deepcopy']
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
用help获取帮助 文档
库参考可以在线浏览 (),并且提供下载,其他一些标准文档(比如Python指南或者Python语言参考)也是如此。所有这些文档都可以在Python网站()找到。
标准库
fileinput模块
实例:为pythonb脚本添加行号
#aa2.py
import fileinput
for line in fileinput.input(inplace=True):
line=line.rstrip()
num=fileinput.lineno()
print '%-50s # %2i' % (line,num)
其中inplace=True,把参数inplace设为真值,表示进行原地处理
集合
求集合的并集实例:
>>> mySet=[]
>>> for i in range(10):
mySet.append(set(range(i,i+5)))
>>> 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]), set([8, 9, 5, 6, 7]), set([8, 9, 10, 6, 7]), set([8, 9, 10, 11, 7]), set([8, 9, 10, 11, 12]), set([9, 10, 11, 12, 13])]
>>> reduce(set.union,mySet)
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])
集合是可变的,所以不能用作字典的键。另外一个问题就是集合本身只能包含不可变(可散列的)值,所以也就不能包含其他集合。有个frozenset类型,用于代表不可变(可散列)的集合:
>>> a=set()
>>> b=set()
>>> a.add(b)
Traceback (most recent call last):
File "
a.add(b)
TypeError: unhashable type: 'set'
>>> a.add(frozenset(b))
>>> a
set([frozenset([])])
双端队列
>>> from collections import deque
>>> q=deque(range(5))
>>> q
deque([0, 1, 2, 3, 4])
>>> q.append(5)
>>> q
deque([0, 1, 2, 3, 4, 5])
>>> q.appendleft(6)
>>> q
deque([6, 0, 1, 2, 3, 4, 5])
>>> q.pop()
5
>>> q
deque([6, 0, 1, 2, 3, 4])
>>> q.popleft()
6
>>> q
deque([0, 1, 2, 3, 4])
>>> q.rotate(3)
>>> q
deque([2, 3, 4, 0, 1])
>>> q.rotate(-1)
>>> q
deque([3, 4, 0, 1, 2])
>>>
时间
随机数
>>> import time
>>> time.asctime()
'Mon Oct 03 16:06:05 2011'
>>> from random import *
>>> from time import *
>>> date1=(2008,1,1,0,0,0,-1,-1,-1)
>>> time1=mktime(date1)
>>> time1
1199116800.0
>>> date2=(2009,1,1,0,0,0,-1,-1,-1)
>>> time2=mktime(date2)
>>> time2
1230739200.0
>>> random_time=uniform(time1,time2)
>>> random_time
1214187035.5437927
>>> local_time=localtime(random_time)
>>> local_time
time.struct_time(tm_year=2008, tm_mon=6, tm_mday=23, tm_hour=10, tm_min=10, tm_sec=35, tm_wday=0, tm_yday=175, tm_isdst=0)
>>> asc_time=asctime(local_time)
>>> asc_time
'Mon Jun 23 10:10:35 2008'
shelve 潜在的陷阱
简单的数据库应用例子
# database.py
import sys, shelve
def store_person(db):
"""
Query user for data and store it in the shelf object
"""
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 number: ')
db[pid] = person
def lookup_person(db):
"""
Query user for ID and desired field, and fetch the corresponding data from
the shelf object
"""
pid = raw_input('Enter ID number: ')
field = raw_input('What would you like to know? (name, age, phone) ')
field = field.strip().lower()
print field.capitalize() + ':', \
db[pid][field]
def print_help():
print 'The available commands are:'
print 'store : Stores information about a person'
print 'lookup : Looks up a person from ID number'
print 'quit : Save changes and exit'
print '? : Prints this message'
def enter_command():
cmd = raw_input('Enter command (? for help): ')
cmd = cmd.strip().lower()
return cmd
def main():
database = shelve.open('C:\\database.txt') # You may want to change this name
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()
re---正则表达式
点号可以匹配“任何字符串”(除换行符外的任何单个字符),所以把点号称为通配符(wildcard)。
++++++++++++++++++++++++++++++++++++++++++++++++++
替换
++++++++++++++++++++++++++++++++++++++++++++++++++
re.escape是一个很是实用的函数,它可以对字符串中所有可能被解释为正则运算符的字符进行转义的应用函数。
+++++++++++++++++++++++++++++++++++++++++++++++++++
作为替换的组号和函数
>>> pat='\*([^\*]+)\*'
>>> re.sub(pat,'\1','*world*')
'\x01'
>>> pat=r'\*([^\*]+)\*'
>>> re.sub(pat,r'\1','hello,*world*')
'hello,world'
寻找发件人的程序:
# find_sender.py
import fileinput, re
print 'hello world'
pat = re.compile('From: (.*) <.*?>$')
for line in fileinput.input():
m = pat.match(line)
if m: print m.group(1)
if m: print line
模板系统示例:
# templates.py
import fileinput, re
# Matches fields enclosed in square brackets:
#field_pat = re.compile(r'\[(.+?)\]') # 修改by ly21st
field_pat=r'\[(.+?)\]'
# We'll collect variables in this:
scope = {}
# This is used in re.sub:
def replacement(match):
code = match.group(1)
try:
# If the field can be evaluated, return it:
return str(eval(code, scope))
except SyntaxError:
# Otherwise, execute the assignment in the same scope...
exec code in scope
# ...and return an empty string:
return ''
# Get all the text as a single string:
# (There are other ways of doing this; see Chapter 11)
lines = []
for line in fileinput.input():
lines.append(line)
text = ''.join(lines)
# Substitute all the occurrences of the field pattern:
#print field_pat.sub(replacement, text)
print re.sub(field_pat,replacement,text) #修改by ly21st