六、包与模块
1.模块module
Python中每一个.py脚本定义一个模块,所以我们可以在一个.py脚本中定义一个实现某个功能的函数或者脚本,这样其他的.py脚本就可以调用这个模块了。调用的方式有三种,如下:
## package and module ####
## a .py file define a module which can be used in other script
## as a script, the name of module is the same as the name of the .py file
## and we use the name to import to a new script
## e.g., items.py, import items
## python contains many .py files, which we can import and use
# vi cal.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 answer is: ", add(3, 5)
if __name__ == "__main__"
r = add(1, 3)
print r
# vi test.py
import cal # will expand cal.py here
# so, this will execute the following code in cal.py
# print "Your answer is: ", add(3, 5)
# it will print "Your answer is: 8"
# but as we import cal.py, we just want to use those functions
# so the above code can do this for me, the r=add(1, 3) will not execute
result = cal.add(1, 2)
print result
# or
import cal as c
result = c.add(1, 2)
# or
from cal import add
result = add(1, 2)
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,在代码中常简写为regex、regexp或RE),计算机科学的一个概念。正则表达式使用单个字符串来描述、匹配一系列符合某个句法规则的字符串。在很多文本编辑器里,正则表达式通常被用来检索、替换那些符合某个模式的文本。
Python提供了功能强大的正则表达式引擎re,我们可以利用这个模块来利用正则表达式进行字符串操作。我们用import re来导入这个模块。
正则表达式包含了很多规则,如果能灵活的使用,在匹配字符串方面是非常高效率的。更多的规则,我们需要查阅其他的资料。
1.元字符
很多,一些常用的元字符的使用方法如下:
## 正则表达式 RE
## re module in python
import re
rule = r'abc' # r prefix, the rule you want to check in a given string
re.findall(rule, "aaaaabcaaaaaabcaa") # return ['abc', 'abc']
# [] 用来指定一个字符集 [abc] 表示 abc其中任意一个字符符合都可以
rule = r"t[io]p"
re.findall(rule, "tip tep twp top") # return ['tip', 'top']
# ^ 表示 补集,例如[^io] 表示除i和o外的其他字符
rule = r"t[^io]p"
re.findall(rule, "tip tep twp top") # return ['tep', 'twp']
# ^ 也可以 匹配行首,表示要在行首才匹配,其他地方不匹配
rule = r"^hello"
re.findall(rule, "hello tep twp hello") # return ['hello']
re.findall(rule, "tep twp hello") # return []
# $ 表示匹配行尾
rule = r"hello$"
re.findall(rule, "hello tep twp hello") # return ['hello']
re.findall(rule, "hello tep twp") # return []
# - 表示范围
rule