`

python常用模块

阅读更多
#!/usr/bin/python
# -*-coding:utf-8-*-

import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )

import time
import pprint,pickle
import sys,os,glob,re,math,random

#from urllib2.request import urlopen
import smtplib

from array import array
from collections import deque
import bisect
from heapq import heapify, heappop, heappush

from string import Template

from timeit import Timer


print dir(time)

#文件读写
#文件只读标记为r,只写标记为w,r+表示可读可写,a表示添加到文件结尾,b表示用二进制的方式打开
fs = open("d:/linkd.txt",'r+')
while fs.readline()!='':
	fs.readline()
    #fs.write("hello world")
fs.close()

#pickle模块
#封装
list_01 = [0,1,2,3,4,5,6]
dict_02 = {"name":"limengyu","age":18,"play":"soccer"}
pk = open("d:/9900.pkl","wb",True)
pickle.dump(list_01,pk)
pickle.dump(dict_02,pk)
pk.close()
#拆封
pk = open("d:/9900.pkl","rb")
data = pickle.load(pk)
pprint.pprint(data)
data = pickle.load(pk)
pprint.pprint(data)
pk.close()

#操作系统接口
print os.getcwd()#获取当前工作目录
os.system('mkdir today1')#创建目录
#print dir(os)
#help(os)

#文件通配符
print glob.glob('*.py')

#命令行参数
#>>pythom2.7 dome.py param1 param2 param3
#>>import sys
print sys.argv
#>>['demo.py','param1','param2','param3']

#错误输出重定向和程序终止
sys.stderr.write(" Warning,log file not found!")
#sys.exit()#退出

#字符串模式匹配
result = re.findall(r' \bf[a-z]*',"which foot or hand fell fastest")
print result
result = "AAABBBBCCCC".replace("AAA","DDD")
print result

#数学
print math.pi
print math.cos(math.pi/4)
print math.log(1024,2)
#Random 模块为生成随机选择提供了工具
print random.choice(["apple","blackberry","soso"])
print random.sample(range(100),10)
print random.random() #random float
print random.randrange(10) #random integer chosen from range(6)

#互联网访问
#for line in urlopen('http://www.baidu.com'):
#    line = line.decode('utf-8')
#    print line

#邮件
#server = smtplib.SMTP('localhost')
#server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
#    """To: jcaesar@example.org
#    From: soothsayer@example.org
#    Beware the Ides of March.
#    """)
#server.quit()

#列表工具
a = array('H',[100,300,200,400])
print sum(a)
print a[1:3]
b = [100,300,200,400]
print b[1:3]
#Collections 模块通过方法depue()提供了一个类似列表对象,它从左边开始能更加快速添
#加和删除,但是在中间查询时很慢。这些对象很适合实现队列和广度优先查询。
d = deque(["test1","test2","test3"])
d.append("test4")
print d.popleft()

#处理排序列表的bisect模块
scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]
bisect.insort(scores, (50, 'ruby'))
print scores

#Headpq 模块为基于正规列表的堆实现提供了函数。最小的值入口总是在位置0上。这对那
#些希望重复访问最小元素而不像做一次完成列表排序的应用过程序很有用。
data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
heapify(data) # rearrange the list into heap order
print data
heappush(data, -5) # add a new entry
print data
print [heappop(data) for i in range(3)] # fetch the three smallest entries


#模板
#String 模块包含一个用途广泛的类,此类为最终用户的编辑提供了简单的语法支持。这让用
#户不修改应用程序的前提下实现他们应用程序的定制。
t = Template('${A}folk send $$10 to $cause.')
print t.substitute(A='Beckham', cause='Giggs')

t = Template('Return the $item to $owner.')
d = dict(item='unladen swallow',owner="Giggs")
print t.substitute(d)


#性能评测
print Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
print Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
print Timer('a,b = b,a', 'a=1; b=2').timeit()

#字符串
#字符串常量可以用不同的方法分在好多行。
#1.可以用反斜杠作为行最后一个字符,用来实现与下一行的逻辑连接
hello = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
Note that whitespace at the beginning of the line is\
significant."
print(hello)
#2.或则,可用一对三个引号或者"'把字符串包围,当运行三个字符串的时候,行尾不是没有转
#义,而是包含着字符中了。
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")

#如果我们想把字符串当做输入字符,\n字符不被转为新行,而是作为代码中的结束符。
#都当做数据包含在字符串中
hello = "This is a rather long string containing\n\
several lines of text much as you would do in C."
hello1 = r"This is a rather long string containing\n\
several lines of text much as you would do in C."
print(hello)
print('\n')
print(hello1)
print('\n')
#字符串还可以用+ 操作符进行相加和* 操作符进行重复。
print 'Help' + 'A'
print '<' + 'word'*5 + '>'
print 'str' 'ing' "..." 'aa'


#正则re模块
# 将正则表达式编译成Pattern对象,注意hello前面的r的意思是“原生字符串”  
pattern = re.compile(r'hello')  
   
# 使用Pattern匹配文本,获得匹配结果,无法匹配时将返回None  
match1 = pattern.match('hello world!')  
match2 = pattern.match('helloo world!')  
match3 = pattern.match('helllo world!')  
  
#如果match1匹配成功  
if match1:  
    # 使用Match获得分组信息  
    print match1.group()  
else:  
    print 'match1匹配失败!'  
  
  
#如果match2匹配成功  
if match2:  
    # 使用Match获得分组信息  
    print match2.group()  
else:  
    print 'match2匹配失败!'  
  
  
#如果match3匹配成功  
if match3:  
    # 使用Match获得分组信息  
    print match3.group()  
else:  
    print 'match3匹配失败!'



a = re.compile(r"""\d +  # the integral part 
                   \.    # the decimal point 
                   \d *  # some fractional digits""", re.X)  
b = re.compile(r"\d+\.\d*")
match11 = a.match('3.1415')  
match12 = a.match('33')  
match21 = b.match('3.1415')  
match22 = b.match('33')   
  
if match11:  
    # 使用Match获得分组信息  
    print match11.group()  
else:  
    print u'match11不是小数'  
      
if match12:  
    # 使用Match获得分组信息  
    print match12.group()  
else:  
    print u'match12不是小数'  
      
if match21:  
    # 使用Match获得分组信息  
    print match21.group()  
else:  
    print u'match21不是小数'  
  
if match22:  
    # 使用Match获得分组信息  
    print match22.group()  
else:  
    print u'match22不是小数' 


m = re.match(r'hello', 'hello world!')  
print m.group() 

#re模块还提供了一个方法escape(string),用于将string中的正则表达式元字符如*/+/?等之前加上转义符再返回

#match
# 将正则表达式编译成Pattern对象  
pattern = re.compile(r'hello')  
# 使用Pattern匹配文本,获得匹配结果,无法匹配时将返回None  
match = pattern.match('hello world!') 
if match:  
    # 使用Match获得分组信息  
    print match.group()  
### 输出 ###  
# hello  

#search
#search(string[, pos[, endpos]]) | re.search(pattern, string[, flags]): 
#这个方法用于查找字符串中可以匹配成功的子串。
# 将正则表达式编译成Pattern对象  
pattern = re.compile(r'world')  
# 使用search()查找匹配的子串,不存在能匹配的子串时将返回None  
# 这个例子中使用match()无法成功匹配  
match = pattern.search('hello world!')
if match:
    # 使用Match获得分组信息  
    print match.group()
### 输出 ###  
# world 

#split
#split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]):
#按照能够匹配的子串将string分割后返回列表。
#maxsplit用于指定最大分割次数,不指定将全部分割。
p = re.compile(r'\d+')  
print p.split('one1two2three3four4') 
### output ###  
# ['one', 'two', 'three', 'four', ''] 

#findall
#findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]):
#搜索string,以列表形式返回全部能匹配的子串。
p = re.compile(r'\d+')  
print p.findall('one1two2three3four4')   
### output ###  
# ['1', '2', '3', '4'] 

#finditer
#finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]):
#搜索string,返回一个顺序访问每一个匹配结果(Match对象)的迭代器。
p = re.compile(r'\d+')  
for m in p.finditer('one1two2three3four4'):  
    print m.group(),
### output ###  
# 1 2 3 4  


#sub
#sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]):
#使用repl替换string中每一个匹配的子串后返回替换后的字符串。 
#当repl是一个字符串时,可以使用\id或\g<id>、\g<name>引用分组,但不能使用编号0。 
#当repl是一个方法时,这个方法应当只接受一个参数(Match对象),并返回一个字符串用于替换(返回的字符串中不能再引用分组)。 
#count用于指定最多替换次数,不指定时全部替换。
p = re.compile(r'(\w+) (\w+)')  
s = 'i say, hello world!'    
print p.sub(r'\2 \1', s)     
def func(m):  
    return m.group(1).title() + ' ' + m.group(2).title()  
print p.sub(func, s)  
### output ###  
# say i, world hello!  
# I Say, Hello World! 


#subn
#subn(repl, string[, count]) |re.sub(pattern, repl, string[, count]):
#返回 (sub(repl, string[, count]), 替换次数)。
p = re.compile(r'(\w+) (\w+)')  
s = 'i say, hello world!'  
print p.subn(r'\2 \1', s)  
def func(m):  
    return m.group(1).title() + ' ' + m.group(2).title()  
print p.subn(func, s)  
### output ###  
# ('say i, world hello!', 2)  
# ('I Say, Hello World!', 2) 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics