六、包与模块
1、模块module
Python中每一个.py脚本定义一个模块,所以我们可以在一个.py脚本中定义一个实现某种功能的函数或者脚本,这样其他的.py脚本就可以条用这个模块了。
def add(x, y):
return x+y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
return x / y
print "your answei is:", add(3,5)
import cal
result = cal.add(1, 2)
print result
import cal as c
result = c.add(1, 2)
from cal import add\
result = add(1, 2)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
2、 包package
python中每个.py文件执行某种功能,那有时候我们需要多个.py完成某个更大的功能,或者我们需要将同类功能的.py文件组织到一个地方,这样就可以方便我们的使用。模块可以按目录组织成包,创建一个包的步骤:
(1)建立一个名字为包名的文件夹
(2)在该文件夹下创建一个init.py空文件
(3)根据需要在该文件夹下存放.py脚本文件、已编译扩展及子包
(4)import pack.m1, pack.m2, pack.m3
#### package 包
## python 的模块可以按目录组织为包,创建一个包的步骤:
# 1、建立一个名字为包名字的文件夹
# 2、在该文件夹下创建一个__init__.py 空文件
# 3、根据需要在该文件夹下存放.py脚本文件、已编译拓展及子包
# 4、import pack.m1, pack.m2 pack.m3
mkdir calSet
cd calSet
touch __init_.py
cp cal.py .
# vi test.py
import calSet.cal
result = calSet.cal.add(1, 2)
print result
七、正则表达式
正则表达式,(英语:RegularExpression,在代码中常简写为reges、regexp或RE),计算机科学的一个概念。正则表达式使用的单个字符来描述、匹配一系列符合某个句法规则的字符串。在很多文本编译器里,正则表达式通常被用来检索、替换那些符合某个某事的文本。
Python提供了功能强大的正则表达式引擎re,我们可以利用这个模块来使用正则表达式进行字符串操作。我们用 import re来导入这个模块。
正则表达式包含了很多规则,如果能灵活的使用,在匹配字符串方面是非常高效率的,更多的规则,我们需要查阅其他的资料。
1、元字符
很多,一些常用的元字符的使用方法如下:
import re
rule = r'abc'
re.findall(rule, "aaaaabcaaaaaabcaa")
rule = r"t[io]p"
re.findall(rule, "tip tep twp top")
rule = r"t[^io]p"
re.findall(rule, "tip tep twp top")
rule = r"^hello"
re.findall(rule, "hello tep twp hello")
re.findall(rule, "tep twp hello")
rule = r"hello$"
re.findall(rule, "hello tep twp hello")
re.findall(rule, "hello tep twp")
rule = r"x[0123456789]x"
rule = r"x[0-9]x"
re.findall(rule, "x1x x4x xxx")
rule = r"x[a-zA-Z]x"
rule = r"\^hello"
re.findall(rule, "hello twp ^hello")
rule = r"^020-\d\d\d\d\d\d\d\d$"
rule = r"^020-\d{8}$"
rule = r"^020-[0-9]{8}$"
re.findall(rule, "020-23546813")
rule = r"ab*"
re.findall(rule, "a")
re.findall(rule, "ab")
rule = r"ab+"
re.findall(rule, "a")
re.findall(rule, "ab")
re.findall(rule, "abb")
rule = r"^020-?\d{8}"
re.findall(rule, "02023546813")
re.findall(rule, "020-23546813")
re.findall(rule, "020--23546813")
rule = r"ab+?"
re.findall(rule, "abbbbbbb")
rule = r"a{1,3}"
re.findall(rule, "a")
re.findall(rule, "aa")
re.findall(rule, "aaa")
re.findall(rule, "aaaa")
rule = r"\d{3,4}-?\d{8}"
re.findall(rule, "020-23546813")
p_tel = re.compile(rule)
p_tel.findall("020-23546813")
name_re = re.compile(r"xiaoyi", re.I)
name_re.findall("Xiaoyi")
name_re.findall("XiaoYi")
name_re.findall("xiAOyi")
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
2、常用函数
Re模块作为一个对象,它还支持很多的操作,例如:
obj = name_re.match('Xiaoyi, Zou')
obj = name_re.search('Zou, Xiaoyi')
if obj:
pass
name_re.findall("Xiaoyi")
name_re.finditer("Xiaoyi")
rs = r"z..x"
re.sub(rs, 'python', 'zoux ni ziox me')
re.subn(rs, 'python', 'zoux ni ziox me')
str = "123+345-32*78"
re.split(r'[\+\-\*]', str)
dir(re)
str = """
hello xiaoyi
xiaoyi hello
hello zou
xiaoyi hello
"""
re.findall(r'xiaoyi', str, re.M)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
3、分组
分组有两个作用,它用()来定义一个组,组内的规则只对组内有效。
email = r"\w{3}@\w+(\.com|\.cn|\.org)"
re.match(email, "zzz@scut.com")
re.match(email, "zzz@scut.cn")
re.match(email, "zzz@scut.org")
另外,分组可以优化返回分组内匹配的字符串
str = """
idk hello name=zou yes ok d
hello name=xiaoyi yes no dksl
dfi lkasf dfkdf hello name=zouxy yes d
"""
r1 = r"hello name=.+ yes"
re.findall(r1, str)
r2 = r"hello name=(.+) yes"
re.findall(r2, str)
4、一个小实例-爬虫
这个实例利用上面的正则和分组的优先返回特性来实现一个小爬虫算法。它的功能是到一个给定的网址里面将.jpg后缀的图片全部下载下来。
import re
import urllib
def getHtml(url):
print 'Getting html source code...'
page = urllib.open(url)
html = page.read()
return html
def getImageAddrList(html):
print 'Getting all address of images...'
rule = r"src=\"(.+\.jpg)\" pic_ext"
imReg = re.compile(rule)
imList = re.findall(imReg, html)
return imList
def getImage(imList):
print 'Downloading...'
name = 1;
for imgurl in imList:
urllib.urlretrieve(imgurl, '%s.jpg' % name)
name += 1
print 'Got ', len(imList), ' images!'
htmlAddr = "http://tieba.baidu.com/p/2510089409"
html = getHtml(htmlAddr)
imList = getImageAddrList(html)
getImage(imList)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
八、深拷贝和浅拷贝
Python中对数据的复制有两个需要注意的差别:
浅拷贝:对引用对象的拷贝(只拷贝对象),深拷贝:对对象资源的拷贝。具体的差别如下:
a = [1, 2, 3]
b = a
a.append(4)
import copy
a = [1, 2, ['a', 'b']]
c = copy.copy(a)
a.append('d')
a[2].append('d')
a[1] = 3
d = copy.deepcopy(a)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
九、文件与目录
1、文件读写
Python的文件操作和其他的语言没有太大的差别。通过open或者file类来访问。但python支持了很多的方法,以支持文件内容和list等类型的交互。具体如下:
fin = open('./test.txt')
fin.read()
fin.close()
fin = file('./test.txt')
fin.read()
fin.close()
fin = open('./test.txt', 'r+')
fin.write('hello')
fin.close()
for i in open('test.txt'):
print i
str = fin.readline()
list = fin.readlines()
fin.next()
fin.writelines(list)
fin.seek(0, 0)
fin.seek(0, 1)
fin.seek(-1, 2)
fin.flush()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
2、OS模块
os模块提供了很多系统操作。例如对目录的操作等。我们需要import os来插入这个模块以便使用。
import os
os.mkdir('xiaoyi')
os.makedirs('a/b/c', mode = 666)
os.listdir()
os.chdir()
os.getcwd()
os.rmdir()
3、目录遍历
目录遍历的实现可以做很多普通的功能,例如杀毒软件,垃圾清除软件,文件搜索软件等等。因为他们都涉及到了扫描某种目录下所有子目录下的文件。所以需要对目录进行遍历。在这里我们可以使用两种方法对目录遍历。
1)递归
import os
def dirList(path):
fileList = os.listdir(path)
allFile = []
for fileName in fileList:
filePath = os.path.join(path, fileName)
if os.path.isdir(filePath):
dirList(filePath)
allFile.append(filePath)
return allFile
2)os.walk函数
# os.walk 返回一个生成器,每次是一个三元组 [目录, 子目录, 文件]
gen = os.walk('/')
for path, dir, filelist in os.walk('/'):
for filename in filelist:
os.path.join(path, filename)
十、异常处理
异常意味着错误,未经处理的异常会终止程序运行。而异常抛出机制,为程序开发人员提供了一种在运行时发现错误,并进行恢复处理,然后继续执行的能力。
try:
fin = open("abc.txt")
print hello
except IOError, msg:
print "On such file!"
except NameError, msg:
print msg
finally:
print 'ok'
if filename == "hello":
raise TypeError("Nothing!!")