Python学习系列(六)(模块)

Python学习系列(六)(模块)

Python学习系列(五)(文件操作及其字典)

一,模块的基本介绍

1,import引入其他标准模块

标准库:Python标准安装包里的模块。

引入模块的几种方式:

       i)引入模块:import   moduleName

       ii)引入模块下的函数:from moduleName import function1,function2,……

       iii)引入模块下的所有函数:from moduleName import *

使用模块里的函数的方法:

     moduleName.function(agrs)

示例:       

1 >>> import math
2 >>> r=math.sqrt(16)
3 >>> print r
4 4.0
View Code

如果模块或者函数名字过长可以在import后使用as给该模块取别名,之后可以通过“别名.函数”使用模块里的函数。

示例:

1 >>> import webbrowser as web
2 >>> web.open_new_tab('http://www.cnblogs.com')
3 True
View Code

2,使用自定义模块

testfile.py下:

1 def readfile():
2     fr=open('wformat.txt','r')
3     while (1==1):
4         line=fr.readline()
5         if(line==''):
6             break
7         else:
8             print line
9     fr.close()
View Code

test.py下:(与testfile.py同在一个目录文件里面

1 import testfile
2 testfile.readfile()
View Code

      结果如图:

1 >>> ===================== RESTART ==============================
2 >>>
3       name age sex
4       张三 78 male
5       李四 50 male
6       王五 80 male
7       张强 90 female
View Code

调用层次结构:

~/|
 
    |tes1.py
#调用“testfile模块的程序文件”tes1.py
    |_test
#目录test
       |_ _testfile.py        
#模块文件testfile.py   
       |_ _testfile.pyc
#模块字节码文件testfile.pyc

      注意.pyc是模块字节码文件,在使用模块是Python解释器需要把模块加载到系统里,若发现.py比.pyc新,则需要重新编译生成.pyc,否则不需要。文件.pyc是在第一次加载模块文件时完成的。

      如果被调用模块程序与模块程序不在同一个目录文件下,则需要调用os.path.append(模块文件所在的目录)

3,使用模块示例Json模块

   1)Python下使用dumps函数可以将Python数据字典转换成Json数据结构。      

Python

Json

dict

object

list,tuple

array

unicode str

str

int,long

number(int)

float

number(real)

True

true

False

false

示例:

1 import json
2 s=[{'f':(1,3,5,'a'),'x':None}]
3 d=json.dumps(s)
4 print d
View Code

结果如图:

1 >>>
2 [{"x": null, "f": [1, 3, 5, "a"]}]
View Code

2)Json数据转换Python数据,解码loads(对应关系如上表)

二,正则模块re

1)正则表达式的常见应用:

  • 验证字符串:如合法的邮件地址,HTTP地址等。
  • 查找字符串
  • 替换字符串
  • 提取字符串

2)基本概念:

     正则表达式:是一段文本或者一个公式,用来描述用某种模式去匹配一类字符串的公式,并且该公式具有一定的模式。

     匹配:给定一段文本或者字符串,使用正则表达式从文本或字符串中查找出符合正则表达式的字符串。有可能文本或字符串存在不止一个部分满足给定的正则表达式,这是每一个这样的部分被称为一个匹配

     元字符:一次只能匹配一个字符或者一个位置。故元字符分:匹配字符的元字符和匹配位置的元字符。

 i)匹配字符的元字符

  • ^string:匹配所有以string字符串开始的行
  • string$:匹配所有以string字符串结尾的行
  • $^:匹配空行
  • Str:匹配以Str开始的单词(等价于<)
  • Str:匹配以Str结尾的单词(等价于>)

 ii)匹配位置的元字符 

  • w:匹配单词里字符(字母,数字和下划线)
  • W:匹配单词里非字符
  • d:匹配单词里数字
  • D:匹配单词里非数字
  • s:匹配单词里空格字符
  • S:匹配单词里非空格字符

示例:

 1 >>> import re
 2 >>> s='Hello www.jeapedu.com'
 3 >>> res=r'jea'
 4 >>> print re.findall(res,s)
 5 ['jea']
 6 >>> res=r'jea'
 7 >>> print re.findall(res,s)
 8 []
 9 >>> res=r'edu'
10 >>> print re.findall(res,s)
11 ['edu']
12  
13 import re
14 s='''
15 ahello
16 www.baidu.com
17 hello world
18  
19 nice hellod world
20 piece of helloe world
21 '''
22 res=r'hello'
23 print 'hello:',re.findall(res,s) 
24 >>> ================================ RESTART ================================
25 >>>
26 hello ['hello', 'hello', 'hello', 'hello']
27  
28 import re
29 s='a1b2c3d'
30 res='wd'
31 print re.findall(res,s)
32 res='wdw'
33 print re.findall(res,s)
34 >>> ================================ RESTART ================================
35 >>>
36 ['a1', 'b2', 'c3']
37 ['a1b', 'c3d']
View Code
     字符集:用方括号括起来的字符集合,如果其中的任何一个字符被匹配,则它就会找到该匹配项,反字符集可在字符前加^
示例:
 1 import re
 2 s='''Plz write a mail to zhangbocheng189@163.com
 3 or 649414754@qq.com,thanks!'''
 4 res=r'w[w.-]+@[w.-]+.w{2,4}'
 5 #*表示匹配0次及其以上,+表示匹配1次及以上。
 6 print re.findall(res,s) 
 7 
 8 >>> ================================ RESTART ================================
 9 >>>
10 ['zhangbocheng189@163.com', '649414754@qq.com']
View Code
     分组或子模式:把一个正则表达式的全部或者部分分成一个或多个组。其中,分组使用的字符是“(”和“)”。
示例:
 1 import re
 2 s='''www.baidu.comwww.BaidU.comwww.bAIDU.comwww.baidu.comwww.Baidu.com'''
 3 res1=r'(b|B)w*(u|U)'
 4 #*表示匹配0次及其以上,+表示匹配1次及以上。
 5 res2=r'[bB]w*(u|U)'
 6 res3=r'[bB]w*[uU]'
 7 print res1+':'
 8 print re.findall(res1,s)
 9 print res2+':'
10 print re.findall(res2,s)
11 print res3+':'
12 print re.findall(res3,s) 
13 
14 >>> ================================ RESTART ================================
15 >>>
16 (b|B)w*(u|U):
17 [('b', 'u'), ('B', 'U'), ('b', 'U'), ('b', 'u'), ('B', 'u')]
18 [bB]w*(u|U):
19 ['u', 'U', 'U', 'u', 'u']
20 [bB]w*[uU]:
21 ['baidu', 'BaidU', 'bAIDU', 'baidu', 'Baidu']
View Code

限定符:用于指定允许特定字符或字符集自身重复出现的次数。

  • (pattern)?:重复0次或者1次,等价于{0,1}
  • (pattern)*:至少重复0次,等价于{0,}
  • (pattern)+:至少重复1次,等价于{1,}
  • (pattern){m:n}:重复至少m次,至多m次
  • (pattern)??:使用重复0次或者1次
  • (pattern)*?:尽可能少地使用重复的第一个匹配
  • (pattern)+?:尽可能少地使用重复但至少使用一次

示例:

 1 import re
 2 s='''Tell to me 110-123-1114119 or call 4008-6688-9988
 3    or 13306247965'''
 4 res=r'd+Dd+Dd+'
 5 #*表示匹配0次及其以上,+表示匹配1次及以上。
 6 res1=r'd{11}'
 7 print re.findall(res,s)
 8 print re.findall(res1,s)
 9 
10 >>> ================================ RESTART ================================
11 >>>
12 ['110-123-1114119', '4008-6688-9988']
13 ['13306247965']
View Code
 通配符:匹配限定长度的字符串,例如点号匹配任意一个字符。
 转义字符:(详见 : Python学习系列(三)(字符串)
3)应用举例:
 1 import re
 2 s='hello www.baidu.com'
 3 print '----------------compile--------------------'
 4 res='[s.]'
 5 pat=re.compile(res)
 6 print pat.findall(s)
 7 print pat.split(s)
 8 print '----------------split--------------------'
 9 res='[s.]'
10 print re.findall(res,s)
11 print re.split(res,s) 
12 
13 >>> ================================ RESTART ================================
14 >>>
15 ----------------compile--------------------
16 [' ', '.', '.']
17 ['hello', 'www', 'baidu', 'com']
18 ----------------split--------------------
19 [' ', '.', '.']
20 ['hello', 'www', 'baidu', 'com']
View Code

三、小结

      本章主要介绍python开发的进阶知识,模块及其正则的相关知识,正则表达式是编程的一个很重要的知识点,需多多研究。

      额外补充一点小知识: 

1,sys模块:包含了与Python的解释器和它的环境有关的函数。
1 import sys
2 for i in sys.argv:
3     print i
4 
5 >>>
6 D:Python学习pythontest	est.py
View Code

2,dir函数:列举模块定义的标识符,如函数、类和变量。当为dir提供一个模块名称的时候,返回模块定义的名称列表,否则返回当前模块中定义的名称列表。

 1 >>> import sys
 2 >>> dir()
 3 ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'i', 'sys']
 4 >>> a=5
 5 >>> dir()
 6 ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'a', 'i', 'sys']
 7 >>> del a   #删除一个变量/名称
 8 >>> dir()
 9 ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'i', 'sys']
10 >>>
View Code
原文地址:https://www.cnblogs.com/zhangbc/p/3901385.html