一、模块
随着程序变得越来越大,为了便于维护,需要把他分为多个文件,为此python允许把定义放入一个文件中,然后在其他程序和脚本中将其作为模块导入。注意:要创建模块可将相关的语句和定义,放入一个与模块同名的文件中
模块示例1:
1 #!/usr/bin/env python
2 def cal(num1,op,num2):
3 if op == "+":
4 return num1+num2
5 elif op == "-":
6 return num1-num2
7 elif op == "*":
8 return num1*num2
9 elif op == "/":
10 return float(num1)/num2
11 else:
12 print "operator error!"
在另一个脚本导入写好的模块
1 #!/usr/bin/env python
2 import cal
3 print cal.cal(1,'+',2)
成功调用
模块示例2.
1 #!/usr/bin/env python
2 #coding=utf-8
3 def westos():
4 return "westos"
5
6 def fentiao():
7 return "fentiao"
8
9 def redhat():
10 return "redhat"
在另一个脚本导包
1 #!/usr/bin/env python
2 #coding=utf-8
3 import westos
4 print westos.redhat()
模块示例3.
怎么把导入的包的本身的输出消掉:
间接调用的__name__=包的文件名
1 #!/usr/bin/env python
2 #coding=utf-8
3 def westos():
4 return "westos"
5
6 def fentiao():
7 return "fentiao"
8
9 def redhat():
10 return "redhat"
11
12 if __name__=="__main__": ##当调用的程序是自身时
13 print fentiao()
1 #!/usr/bin/env python
2 #coding=utf-8
3 import westos
4 print westos.redhat()
运行:
[root@foundation29 code]# python westos.py
fentiao
[root@foundation29 code]# python hello.py
redhat
模块的一些细节:
1.导入多个模块要用","分隔
2.使用不同名称导入模块as:import div as foo
3.将模块内的某一个函数导入from:
from语句用户将模块中的具体定义加载到当前命名空间,from相当与import,但他不会创建一个名称来引用新创建的模块命名空间,而是将对模块中定义的一个或多个对象的引用放到当前命名空间中
from div import divide
1 #!/usr/bin/env python
2 #coding=utf-8
3 from westos import redhat as wu
4 print wu()
4.若导入一个极长的名称列表,可以将名称放在括号内:
from spam import (foo,
bar,
Spam)
5.把模块内的所有内容全部导入的另一中方法:
*通配符也可用于加载模块中的所有定义,但以下划线开头的定义除外
from div import *
1 #!/usr/bin/env python
2 #coding=utf-8
3 from westos import *
4 print redhat() ##可以直接用函数名
6.python库函数:/usr/lib64/python2.7/
[root@foundation29 code]# vim pass.py
[root@foundation29 code]# cat pass.py
#!/usr/bin/env python
import getpass ##导入的是库函数里的getpass
getpass.getpass()
[root@foundation29 code]# python pass.py
Password:
[root@foundation29 code]# vim getpass.py ##在当前路径下创建一个与库函数里的文件相同的文件
[root@foundation29 code]# ls
add.py cal.py cal.pyc getpass.py hello.py pass.py westos.py westos.pyc
[root@foundation29 code]# python pass.py
Traceback (most recent call last):
File "pass.py", line 3, in <module>
getpass.getpass()
AttributeError: 'module' object has no attribute 'getpass' ##此时调用的是当前路径下的getpass,所以会出错
7.找包的流程:当前路径——》库函数/usr/lib64/python2.7/
再举一个例子:
[root@foundation29 code]# cat pass.py
#!/usr/bin/env python
import string
print string.capitalize("sdf")
[root@foundation29 code]# python pass.py
Sdf
[root@foundation29 code]# touch string.py
[root@foundation29 code]# python pass.py
Traceback (most recent call last):
File "pass.py", line 4, in <module>
print string.capitalize("sdf")
AttributeError: 'module' object has no attribute 'capitalize'
建立一个包:
在包里创建文件:__init__.py
[root@foundation29 code]# mkdir mypack
[root@foundation29 code]# vim mypack/__init__.py
将脚本放进去:
[root@foundation29 code]# mv westos.py mypack/
[root@foundation29 code]# vim hello.py
1 #!/usr/bin/env python
2 #coding=utf-8
3 import mypack.westos
4 print mypack.westos.redhat() ##必须把名字写全调用,否则会报错
1 #!/usr/bin/env python
2 #coding=utf-8
3 import mypack.westos as a ##修改名字,能方便,但是不容易读
4 print a.redhat()
1 #!/usr/bin/env python
2 #coding=utf-8
3 from mypack.westos import fentiao,redhat,westos
4 print redhat(),fentiao(),westos()
二、字符串处理
1.分割与连接:
string.split([seq[,2]])
2.默认是以空格为分隔符
In [6]: s.split()Out[6]: ['hello', 'world'] ##返回的是一个列表
3.字符串是不可变对象
In [1]: s="hello"
In [2]: id(s)
Out[2]: 15385296
In [3]: s="world"
In [4]: id(s)
Out[4]: 15386304
4.连接:+,join
分隔符.join(可迭代类型,如元组,列表,字典,字符串)
In [9]: s=["hello","world"]
In [10]: " ".join(s)
Out[10]: 'hello world'
5.find:字符串查找
In [16]: s="kkk jjj iii ooo iii iii iii iii"
In [17]: s.find("iii")
Out[17]: 8
In [18]: s.find("iii",12)
Out[18]: 16
In [19]: s.find("iii",20)
Out[19]: 20
In [20]: s.find("iii",1,8)
Out[20]: -1
In [22]: s.find("iii",1,11)
Out[22]: 8
6.replace():字符串替换
In [34]: s
Out[34]: 'kkk jjj i ooo iii iii iii iii'
In [35]: s.replace("iii","i",2)
Out[35]: 'kkk jjj i ooo i i iii iii'
In [36]: s1="\tsdfs "
In [37]: s1.strip()
Out[37]: 'sdfs'
lstrip():移除字符串左边的空格、制表符
In [39]: s1.lstrip()
Out[39]: 'sdfs '
rstrip():移除字符串右边的空格、制表符
In [40]: s1.rstrip()
Out[40]: '\tsdfs'
练习题:
替换分隔符
In [41]: s="172.24.254.29"
第一种方法:
In [44]: s.replace(":",".")
Out[44]: '172.24.254.29'
第二种方法:
In [43]: ":".join(s.split("."))
Out[43]: '172:24:254:29'
练习:
做一个备份
1 #!/usr/bin/env python
2 import os
3 back_file=[]
4 in1=raw_input("please input file:")
5 while in1 is not "":
6 back_file.append(in1)
7 in1=raw_input("continue input file,stop press Enter:")
8 dstBackDir="/mnt/"
9
10 for file in back_file:
11 n=os.system("cp -p %s %s" %(file,dstBackDir))
12 if n==0:
13 print file," sucessful"
14 else:
15 print file," failed"
运行:
[root@foundation29 code]# python beifen.py
please input file:/root/code/cal.py
continue input file,stop press Enter:
/root/code/cal.py sucessful
[root@foundation29 code]# python beifen.py
please input file:/root/code/cal.py
continue input file,stop press Enter:/root/code/hello.py
continue input file,stop press Enter:
/root/code/cal.py sucessful
/root/code/hello.py sucessful
三、正则表达式
1.元字符
. ^ $ * + ? {} [] \ | ()
\:转义,使特殊字符表达他本来的意思,
注意:元字符在字符集中不起作用>>> s='tap tbp tcp tdp'
>>> r=r't[ac]p'
>>> re.findall(r,s)
['tap', 'tcp']
>>> r=r't[^ac]p'
>>> re.findall(r,s)
['tbp', 'tdp']
练习:识别字符串,"bit","bat","but","hit","hut","hat"
import re
r=r"[bh][aui]t"
当要匹配的字符串里面含有特殊字符时,要在规则李加转义符“\”
In [49]: r=r"^hello"
In [50]: re.findall(r,"hello")
Out[50]: ['hello']
In [53]: re.findall(r,"^hello")
Out[53]: []
In [55]: r=r"\^hello"
In [56]: re.findall(r,"^hello")
Out[56]: ['^hello']
\d:匹配数字0-9 ##[0-9]
\D:匹配不是数字的其他字符 ##[^0-9]
\s:匹配\t,\r,\n,空格 ##[\t\r\n' ']
\S:匹配不是\t,\r,\n,' '的其他字符 ##[^\t\r\n' ']
\w:匹配大写字母,小写字母,数字 ##[A-Za-z0-9]
\W:匹配不是大写字母,小写字母,数字的其他字符 ##[^A-Za-z0-9]
{}:前一个字符重复几次
In [61]: r="^010-\d\d\d\d\d$"
In [62]: re.findall(r,"010-2222333")
Out[62]: []
In [63]: re.findall(r,"010-2222")
Out[63]: []
In [64]: re.findall(r,"010-2222")
Out[64]: []
In [65]: re.findall(r,"010-22222")
Out[65]: ['010-22222']
In [66]: re.findall(r,"010-222222")
Out[66]: []
In [70]: r="^010-\d{2}$"
In [71]: re.findall(r,"010-2")
Out[71]: []
In [72]: re.findall(r,"010-22")
Out[72]: ['010-22']
In [73]: re.findall(r,"010-222")
Out[73]: []
In [74]: r=r"010-\d{2,3}$"
In [75]: re.findall(r,"010-2")
Out[75]: []
In [76]: re.findall(r,"010-22")
Out[76]: ['010-22']
In [77]: re.findall(r,"010-222")
Out[77]: ['010-222']
In [78]: re.findall(r,"010-2222")
Out[78]: ['010-222']
*:前一个字符重复0次或多次
In [100]: re.findall(r"ab*","a")
Out[100]: ['a']
In [101]: re.findall(r"ab*","ab")
Out[101]: ['ab']
In [102]: re.findall(r"ab*","abbbb")
Out[102]: ['abbbb']
+:前一个字符重复1次或多次
In [97]: re.findall(r"ab+","abbbb")
Out[97]: ['abbbb']
In [98]: re.findall(r"ab+","a")
Out[98]: []
In [99]: re.findall(r"ab+","ab")
Out[99]: ['ab']
?:前一个字符重复0次或1次
In [95]: re.findall(r"^010-?","010-23")
Out[95]: ['010-']
In [96]: re.findall(r"^010-?","010")
Out[96]: ['010']
{m,n} -----> 重复m次到n次
{m} -----> 重复m次
{m,} -----> 重复m次到无穷大次
{,n} -----> 重复0次到n次
{0,} -----> *
{1,} -----> +
{0,1} -----> ?
贪婪模式:正则匹配默认是贪婪模式的
非贪婪模式:加?
In [137]: re.findall (r"ab?","abbbbbbb")
Out[137]: ['ab']
In [138]: re.findall (r"ab+?","abbbbbbb")
Out[138]: ['ab']
+?:匹配1次
练习题:
匹配简单的以“www.”开头,以“.com”结尾的域名
In [103]: r=r"^www\.\w+\.com$"
In [104]: re.findall(r,"www.baidu.com")
Out[104]: ['www.baidu.com']
In [105]: re.findall(r,"www.u.com")
Out[105]: ['www.u.com']
In [106]: re.findall(r,"www..com")
Out[106]: []
In [107]: re.findall(r,"www.ds.c")
Out[107]: []
compile:生成一个规则的对象
In [158]: x = re.compile(r"ab+")
In [159]: x.findall("ab")
Out[159]: ['ab']
忽略大小写:
In [163]: x = re.compile(r"westos",re.I)
In [165]: x.findall("westos")
Out[165]: ['westos']
In [166]: x.findall("westoS")
Out[166]: ['westoS']
match:
In [180]: x
Out[180]: re.compile(r'westos', re.IGNORECASE)
In [181]: x.match("westos file")
Out[181]: <_sre.SRE_Match at 0x2e77e00>
In [182]: x.match("westos")
Out[182]: <_sre.SRE_Match at 0x2f2cd98>
search:
In [185]: x.search("hello westos")
Out[185]: <_sre.SRE_Match at 0x2ebc238>
In [186]: x.search("hello westos")
Out[186]: <_sre.SRE_Match at 0x2ebc3d8>
finditer
In [188]: it = x.finditer("hello westos")
In [189]: it.next()
Out[189]: <_sre.SRE_Match at 0x2f2cf38>
In [190]: it.next() ##只有一个所以会报错
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-190-54f0920595b2> in <module>()
----> 1 it.next()
StopIteration:
group:
In [2]: x = re.compile(r"westos")
In [4]: x.match("westos")
Out[4]: <_sre.SRE_Match at 0x23c9f38>
In [5]: x.match("westos").group()
Out[5]: 'westos'
In [6]: a = x.match("westos")
start:
In [8]: a.start()
Out[8]: 0
end:
In [9]: a.end()
Out[9]: 6
span:
In [10]: a.span()
Out[10]: (0, 6)
sub:
In [11]: s = "hello fentiao"
In [13]: re.sub(r"fent..o","linux",s)
Out[13]: 'hello linux'
In [14]: s
Out[14]: 'hello fentiao'
In [15]: re.sub(r"fent..o","linux",s+"fenttto")
Out[15]: 'hello linuxlinux'
In [16]: re.sub(r"fent..o","linux",s+" fenttto")
Out[16]: 'hello linux linux'
subn:
In [17]: re.subn(r"fent..o","linux",s+" fenttto")
Out[17]: ('hello linux linux', 2)
In [18]: s = "1+2-4*3/4"
split:
In [19]: re.split(r"[\+\-\*/]","12+3-4*4/5")
Out[19]: ['12', '3', '4', '4', '5']
编译标志:
re.I ##忽略大小写
In [20]: re.findall(r"westos","westos Westos",re.I)
Out[20]: ['westos', 'Westos']
re.S ##匹配\n时
In [24]: re.findall(r"west.s","west\ts")
Out[24]: ['west\ts']
In [25]: re.findall(r"west.s","west\rs")
Out[25]: ['west\rs']
In [26]: re.findall(r"west.s","west\ns")
Out[26]: []
In [27]: re.findall(r"west.s","west s")
Out[27]: ['west s']
In [28]: re.findall(r"west.s","west\ns",re.S)
Out[28]: ['west\ns']
re.M ##有多行内容时
In [33]: s = '''
....: hello westos
....: westos hello
....: westos linux
....: '''
In [34]: re.findall(r"^westos",s)
Out[34]: []
In [35]: re.findall(r"^westos",s,re.M)
Out[35]: ['westos', 'westos']
re.X ##忽略各种制表符
In [36]: r = """
....: ^010
....: -?
....: \d{7}
....: """
In [40]: r
Out[40]: '\n^010\n-?\n\\d{7}\n'
In [37]: re.findall(r,"010-231232")
Out[37]: []
In [38]: re.findall(r,"010-2312328")
Out[38]: []
In [39]: re.findall(r,"010-2312328",re.X)
Out[39]: ['010-2312328']
分组:
In [56]: email_r = r"^www\.\w+\.(com|edu|net)"
In [57]: re.search(email_r,"www.hello.net").group()
Out[57]: 'www.hello.net'
In [58]: re.search(email_r,"www.hello.edu").group()
Out[58]: 'www.hello.edu'
In [59]: re.findall(email_r,"www.hello.edu")
Out[59]: ['edu']
In [60]: s = """
....: hello src="www.westos.org" yes hello
....: ok hello src="www.eeww.com" yes
....: """
In [61]: r = r"hello src=.+ yes"
In [62]: re.findall(r,s)
Out[62]: ['hello src="www.westos.org" yes', 'hello src="www.eeww.com" yes']
In [63]: re.findall(r,s)
KeyboardInterrupt
In [63]: r = r"hello src=(.+) yes"
In [64]: re.findall(r,s)
Out[64]: ['"www.westos.org"', '"www.eeww.com"']