Python 模块 (10) 持续更新

模块

增加解释器寻找模块的路径

Window

import sys
sys.path.append('c:/python')

UNIX

import sys
sys.path.append('/home/yourusername/python')
sys.path.append('~/python')

比如保存了一个文件 hello.py 保存在 c:/python。内容为

print 'Hello World!'

然后我们就这样导入自己的模块

import sys
sys.path.append('c:/python')

import hello

输出

Hello World!

导入模块是,会生成hello.pyc文件。这个文件是编译过后的文件,删除它,不会损害程序,计算机会重新创建它。

导入模块,只有在第一次导入的时候,执行的某些操作如(打印),才执行,第二次执行是不会执行的。如

import hello
import hello

打印只会输出一遍。

如果坚持需要重新载入模块,可以

hello = reload(hello)

这样重新载入就替换了原先的版本。

在Python3.0中,已经去掉了reload函数,只能通过exec实现同样功能。尽可能避免重新载入模块。

如果希望模块能像程序一样执行。可以用

python -m progname args

progname 是模块,-m切换执行程序,args 命令行参数。

import hello 这样模块里面定义的函数,就在模块作用域内定义了。

def fun():
    print 'module hello call fun'

输出

import hello
hello.fun()

为了代码更加重用,将它模块化更重要。

模块中测试代码

在模块中 __name__变量名是模块名字时,此时是导入模块,如果变量名是 __main__ ,那么就是作为程序执行的 。

那么就可以通过条件测试代码模块

if __name__ == '__main__':
    fun()

打印Python查找模块的路径

import sys,pprint

pprint.pprint(sys.path)

在PYTHONPATH环境变量中包含模块所在的目录

Window

右击计算机属性--->点击高级系统设置-->选择高级选项卡-->点击环境变量-->在用户变量中 点击 新建变量名为 PYTHONPATH ,目录作为 变量值 ,多个目录已 分号 隔开。 (如果有直接修改变量值)

比如 我目录值 为 E:\python。 这时候在输出 sys.path ,就会多出 E:\python 。如果没有,需要重新启动一下,程序,还是没有重新启动电脑。

UNIX和Max OSX中

可以在每次登陆都要执行的shell文件内设置环境变量。如类似bash的shell文件。

还可以设置 .bashrc 可以在主目录中找到它。将下面的命令添加到这个文件,从而将 ~python/python加入到PYTHONPATH:

export PYTHONPATH=$PYTHONPATH:~/python

 

你还可以不需要使用PYTHONPATH来更改sys.path,还可以用路径配置文件以.pth为扩展名的文件。

首先我先查一下 配置放的目录中

import site,sys
print sys.prefix

比如上述代码输出 D:\Python27

然后我们在 这个目录里,新建文件 名为 test_pth.pth

内容为

E:\python1
E:\python2

这些模块会在Python解释器初始化时自动导入。在打印 sys.path 时, 就会出现这两个路径。

类似的介绍内容,可以看

http://v2in.com/pth-file-usage-in-python.html

模块的命名

模块代码的文件的名字要和模块名一样,扩展名为.py 。Window中还可以.pyw为扩展名。

介绍的文章,还可以看

http://blog.csdn.net/feeltouch/article/details/45952003

http://zhidao.baidu.com/question/2315147.html

为了让Python作为包对象,包的目录必须包含一个名为 __init__.py文件。

http://www.cnblogs.com/feeland/p/4401758.html

http://www.cnblogs.com/bangbangjiang/p/3418077.html

http://blog.csdn.net/leexide/article/details/39908279

__init__.py 内容为

__all__ = ["aa","bb"]

使用Dir函数查看包内容

import copy

print dir(copy)
print [n for n in dir(copy) if not n.startswith('_')]

查看包模块

print copy.__all__

 

---恢复内容结束---

模块

增加解释器寻找模块的路径

Window

import sys
sys.path.append('c:/python')

UNIX

import sys
sys.path.append('/home/yourusername/python')
sys.path.append('~/python')

比如保存了一个文件 hello.py 保存在 c:/python。内容为

print 'Hello World!'

然后我们就这样导入自己的模块

import sys
sys.path.append('c:/python')

import hello

输出

Hello World!

导入模块是,会生成hello.pyc文件。这个文件是编译过后的文件,删除它,不会损害程序,计算机会重新创建它。

导入模块,只有在第一次导入的时候,执行的某些操作如(打印),才执行,第二次执行是不会执行的。如

import hello
import hello

打印只会输出一遍。

如果坚持需要重新载入模块,可以

hello = reload(hello)

这样重新载入就替换了原先的版本。

在Python3.0中,已经去掉了reload函数,只能通过exec实现同样功能。尽可能避免重新载入模块。

如果希望模块能像程序一样执行。可以用

python -m progname args

progname 是模块,-m切换执行程序,args 命令行参数。

import hello 这样模块里面定义的函数,就在模块作用域内定义了。

def fun():
    print 'module hello call fun'

输出

import hello
hello.fun()

为了代码更加重用,将它模块化更重要。

模块中测试代码

在模块中 __name__变量名是模块名字时,此时是导入模块,如果变量名是 __main__ ,那么就是作为程序执行的 。

那么就可以通过条件测试代码模块

if __name__ == '__main__':
    fun()

打印Python查找模块的路径

import sys,pprint

pprint.pprint(sys.path)

在PYTHONPATH环境变量中包含模块所在的目录

Window

右击计算机属性--->点击高级系统设置-->选择高级选项卡-->点击环境变量-->在用户变量中 点击 新建变量名为 PYTHONPATH ,目录作为 变量值 ,多个目录已 分号 隔开。 (如果有直接修改变量值)

比如 我目录值 为 E:\python。 这时候在输出 sys.path ,就会多出 E:\python 。如果没有,需要重新启动一下,程序,还是没有重新启动电脑。

UNIX和Max OSX中

可以在每次登陆都要执行的shell文件内设置环境变量。如类似bash的shell文件。

还可以设置 .bashrc 可以在主目录中找到它。将下面的命令添加到这个文件,从而将 ~python/python加入到PYTHONPATH:

export PYTHONPATH=$PYTHONPATH:~/python

 

你还可以不需要使用PYTHONPATH来更改sys.path,还可以用路径配置文件以.pth为扩展名的文件。

首先我先查一下 配置放的目录中

import site,sys
print sys.prefix

比如上述代码输出 D:\Python27

然后我们在 这个目录里,新建文件 名为 test_pth.pth

内容为

E:\python1
E:\python2

这些模块会在Python解释器初始化时自动导入。在打印 sys.path 时, 就会出现这两个路径。

类似的介绍内容,可以看

http://v2in.com/pth-file-usage-in-python.html

模块的命名

模块代码的文件的名字要和模块名一样,扩展名为.py 。Window中还可以.pyw为扩展名。

介绍的文章,还可以看

http://blog.csdn.net/feeltouch/article/details/45952003

http://zhidao.baidu.com/question/2315147.html

为了让Python作为包对象,包的目录必须包含一个名为 __init__.py文件。

http://www.cnblogs.com/feeland/p/4401758.html

http://www.cnblogs.com/bangbangjiang/p/3418077.html

http://blog.csdn.net/leexide/article/details/39908279

__init__.py 内容为

__all__ = ["aa","bb"]

使用Dir函数查看包内容

import copy

print dir(copy)
print [n for n in dir(copy) if not n.startswith('_')]

查看包模块

print copy.__all__

help 查看帮助

print help(copy.copy)
print copy.copy.__doc__
print copy.__file__

__doc__ 查看文档

__file__ 查看源代码位置

打开文件查看时候,确保没有保存修改内容。有一些特殊的模块是无法查看,如内置在解释器中的 sys 和 C语言写的扩展。

丰富的标准库

sys模块

sys.argv  命令行参数

sys.exit   退出当前程序

sys.modules  输出当前导入的模块

sys.path     当前模块的路径 

sys.platform  当前运行的平台名称

os模块

os.environ['PYTHONPATH']  可以映射更改系统环境变量,不过不是所有的系统都支持

os.sysytem('cls')      在shell中执行命令

os.system('calc')

os.sep           输出 路径名 分隔符 

os.pathsep          输出 分割路径 符

os.linesep         输出 文本文件换行符

os.urandom(n)        产生n字节的字符串,可以作为随机加密key

 

>>> os.system(r'C:\Program Files (x86)\2345Soft\2345Pic\2345Pic.exe')
'C:\Program' 不是内部或外部命令,也不是可运行的程序
或批处理文件。

参数里面包含空格就会停下来。

这是可以用 startfile 来代替它,有空格也没有关系

os.startfile(r'C:\Program Files (x86)\2345Soft\2345Pic\2345Pic.exe')

在Window中,Python执行 os.system 或 os.startfile 后,python任然继续执行。在UNIX中,程序则会终止,等待os.system命令完成。

如果我们只是打开浏览器,可以用 webbrowser 模块

>>> import webbrowser
>>> webbrowser.open('www.baidu.com')
True

 

fileinput 模块

遍历文本所有行,在UNIX命令下

python some_script.py file1.txt file2.txt file3.txt

还可以用标准的UNIX命令 cat :

cat file.txt | python some_script.py

使用 fileinput模块,在UNIX管道中使用cat调用脚本效果和将文件名作为命令行参数提供给脚本是一样的。

  1. fileinput.input  返回for循环遍历对象
  2. filename      返回文件名
  3. lineno          返回当前(累计的)行数
  4. filelineno         返回当前文件的行数
  5. isfirstline         检查当前行是否是文件的第一行
  6. isstdin             检查最后一行是否来自sys.stdin
  7. nextfile           关闭当前文件,移动到下一个文件
  8. close              关闭当前文件

 示例

test2.py

import fileinput

for line in fileinput.input(inplace=True):  # inplace 将标准输出结果写回文件
    line = line.rstrip()             # 删除末尾空格字符
    num = fileinput.lineno()         # 返回当前行数
    print '%-60s # %2i' % (line , num)  # 格式化字符串

运行 python test2.py hello.py

运行之后 hello.py 每一行的末尾都会加上 # 行号

关于格式化字符串忘记的话,可以再看下这篇文章

http://www.cnblogs.com/z888/p/5688972.html

 

更多的介绍

http://blog.csdn.net/jerry_1126/article/details/41926407

https://laike9m.com/blog/python-fileinput-shi-yong-zong-jie,23/

集合、堆和双堆队列

集合

>>> set(range(10))
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

找出两个集合并集  | 或运算符

a = set([1,2,3])
b = set([1,2,4])
print a.union(b)
print a | b

集合方法 

issubset 一个set是否包含另一个set

a = set([1,2])
b = set([1,2,4])
print a.issubset(b)    # True
print b >= a       # True 

issuperset 判断一个集合包含了另一个集合的所有元素

a = set([1,2])
b = set([1,2,4])

print b.issuperset(a)   #True

intersection 返回两个集合共有元素

a = set([1,2])
b = set([1,2,4])

print b.intersection(a)  #  set([1, 2])
print b & a              #  set([1, 2]) 

difference 返回一个集合中不存在于另一个集合中的元素

a = set([1,2])
b = set([1,2,4])

print b.difference(a)  #  set([4])
print b - a              #  set([4])

symmetric_difference  返回两个集合中所有不存在于对方的元素

a = set([1,2,3])
b = set([1,2,4])

print b.symmetric_difference(a)  #  set([3,4])
print b ^ a                      #  set([3,4])

copy 创建一个集合副本

a = set([1,2])

print a.copy()          # set([1, 2])
print a.copy() is a     # False

is 函数 判断两个对象的内存地址是否相同。下面有三个关于is函数的介绍

https://segmentfault.com/q/1010000000315026

http://www.iplaypython.com/jinjie/is.html

https://www.liurongxing.com/python-is-cmp-compare-operator.html

集合的基本方法,还有 add 和 remove。更过的大家的可以参考官方手册。

打印多个集合的交集

reduce(function, sequence, initial=None)

mySets = []
for i in range(10):
    mySets.append(set(range(i, i+5)))

print reduce(set.union, mySets)

 

集合是可变的,所以不能用做字典的键。集合本身值能包含不可变的值。如果我们需要在集合里面放集合的话,可以用 frozenset 创建 不可变集合。

>>> a = set()
>>> b = set()
>>> a.add(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
>>> a.add(frozenset(b))

frozenset 创建给定集合的副本,该集合可以做为其他集合成员,还可以作为字典的键。

>>> c = {}
>>> c[frozenset(b)] = 11

堆(heap),优先队列的一种。Python没有独立的堆类型,只有堆操作的模块heapq(q是queue的缩写,即队列)。

heappush(heap, item)      将item入堆

heappop(heap)          将堆中最小元素弹出

heapify(x)            将列表转为堆

heapreplace(heap, item)      将堆中最小的元素弹出,同时将item入堆

nlargest(n, iterable)        返回iterable中第n大的元素

nsmallest(n, iterable)        返回iterable中第n小的元素

由于 heap 是通过列表实现的,我们可以直接用列表创建。

from heapq import *
from random import *

data = range(10)
shuffle(data)
heap = []
for n in data:
    heappush(heap, n)
print heap
heappush(heap, 0.5)
print heap

# 检测 元素排序

for i in range(len(heap)):
    print heap[i], heap[i // 2], i // 2, i

for i in range(len(heap)):
    print heappop(heap)

shuffle 将序列的所有元素随机排序

关于堆元素的顺序,也不是很清楚,等有时间在好好看看。

双端队列(以及其他集合类型)

双堆队列(double-ended queue 或称 deque)在需要按照元素增加的顺序来移动元素时非常有用。Python模块叫deque

通过可迭代对象(比如集合创建)

from collections import deque

q = deque(range(5))
q.append(5)
q.appendleft(6)
print q
q.append(10)
print q
print q.pop()
print q.popleft()
print q
q.rotate(5)
print q
q.rotate(-1)
print q
q.extendleft([99])
print q

输出

deque([6, 0, 1, 2, 3, 4, 5])
deque([6, 0, 1, 2, 3, 4, 5, 10])
10
6
deque([0, 1, 2, 3, 4, 5])
deque([1, 2, 3, 4, 5, 0])
deque([2, 3, 4, 5, 0, 1])
deque([99, 2, 3, 4, 5, 0, 1])

time模块

asctime([tuple])      将时间元组转换为字符串

localtime([secs])      将秒数转换为日期元组,以本地时间为准

mktime(tuple)        将时间元组转为时间戳

sleep(secs)        休眠(不做任何事情) secs秒

strptime(string[,format])  将字符串解析为时间元组

time()            当前时间戳

__timeTuple = time.localtime()
print time.mktime(__timeTuple)
print time.time()

关于与时间密切相关的模块:datetime(支持日期和时间的算法) 和 timeit (帮助开发人员对代码段的执行时间进行计时)

random 模块

random模块返回随机数的函数

random模块所产生的随机都是伪随机数。如果真正的随机性,应该使用os模块的urandom函数。random模块内的SystemRandom类也是基于一样的功能。让数据接近真正的随机性。

random()        返回 0<n<=1之间的随机实数n

getrandbits(n)      以长整形形式返回n个随机位

uniform(a,b)      返回随机实数n,其中a<= n < b

randrange([start],stop,[step] )      返回range(start,stop,step)中的随机数

choice(seq)        从序列seq中返回随意元素

shuffle(seq[,random])    将序列seq元素随机返回

sample(seq,n)      从序列seq中选择n个随机企鹅独立的元素

from time import *
from  random import *

date1 = (2008,1,1,0,0,0,-1,-1,-1)
time1 = mktime(date1)
date2 = (2009,1,1,0,0,0,-1,-1,-1)
time2 = mktime(date2)

random_time = uniform(time1,time2)
print asctime(localtime(random_time))

print uniform(10,100)

shelve模块  在文件中存储数据

shelve.open函数 会返回shelf对象。

不过有个陷阱

import shelve

s = shelve.open('test.dat')
s['x'] = [1,2,3]
s['x'].append(4)
print s['x']

输出的时候,会发现并没有 4

shelf对象中查找元素时,如果根据进行对该元素修改时候时,shelf对象并不会进行存储。解决方案如下

import shelve

s = shelve.open('test.dat')
s['x'] = [1,2,3]
temp = s['x']
temp.append(4)
s['x'] = temp
print s['x']

这个时候,就可以解决了。还可以这样

import shelve

s = shelve.open('test.dat',writeback=True)
s['x'] = [1,2,3]
s['x'].append(4)
print s['x']
s.close()

设置writeback为True时,后面必须调用close方法,才能写回硬盘中。

shelve模块可以做一个非常简单的数据库。

re模块 正则表达式 

正规则表达式是非常重要的一节,它虽然难学不过,不过学会,会发现他很强大。

正规则表达式可以匹配文本片段的模式。

通配符 . 点号

点号(.)可以匹配任何字符(出了换行符)

.ython 匹配 'python'、'+ython'、' ython'

不能匹配 'cpython'  点号只能匹配一个字母,而不是两个或零个。

对特殊字符进行转义

'python\\.org' 匹配 'python.org'

使用双斜杠让解释器进行转义,还可以

r'python\.org'

字符集

使用中扩号扩住字符串来创建字符集

'[pj]ython' 匹配 'python' 和 'jython'

 

'[a-z]' 匹配 a到z 任意一个字符

还可以范围联合使用  '[a-zA-Z0-9]' 匹配 任意大小写字母和数字

匹配 中文字符串范围 就是  [\u4e00-\u9fa5]

反转字符集

在开头使用^字符。

如 '[^abc]' 可以匹配任何除了a、b和c之外的字符。

字符集中的特殊字符

如果要匹配 如何 脱字符^ 、中括号[]、横线 - 。都要用反斜线进行转义。

选择符和子模式

有的时候需要匹配 'python' 和 'perl',不能使用字符集或则通配符来指定某个特定的模式。那么就可以选择符 ( | )。

'python|perl' 匹配 'python' 和 'perl'

有些时候不要对整个模式使用选择运算符,只是模式一部分。那么可以使用圆括号把需要的部分,扩起来。这行为叫 称 子模式。

'p(ython|erl)'  匹配 'python' 和 'perl'

可选项和重复子模式

在子模式后面加上问号,就变成了可选项。作用是可能出现在匹配字符串中,不是必须的。

r'(http://)?(www.)?python\.org' 匹配

'http://www.python.org'

'http://python.org'

'www.python.org'

'python.org'

  • 对点号进行转义,防止它作为通配符使用
  • 使用原始字符串减少所需反斜线的数量
  • 每个可选子模式都用圆括号括起来
  • 每个可选子模式互相独立

问号表示子模式可以出现一次或者根本不出现。还可以使用运算符允许子模式重复多次:

  • (pattern)*             允许模式重复0次或多次
  • (pattern)+        允许模式重复1次或多次
  • (pattern){m,n}     允许模式重复m~n次

r'w*\.python\.org'  匹配 www.python.org、.python.org、wwwwwwwww.python.org

r'w+\.python\.org' 匹配 w.python.org 不匹配.python.org

r'w{3,4}\.python\.org'  匹配 www.python.org、wwww.python.org

字符串的开始和结尾

模式匹配可以针对整个字符串,但如果我们想匹配这个字符串的开始和结尾呢

使用脱字符( ^ ) 标记开始  

'^ht+p' 匹配 'http://python.org'、'htttttttttp://python.org' 不能匹配 'www.http.org'

使用美元符号( $ ) 标记结尾

'$\.org' 匹配 'http://python.org'

开始使用正则表达式

re模块函数

 

compile(pattern[,flags]) 根据包含正规则表达式的字符串创建模式对象
search(pattern,string[,flags]) 在字符串中寻找模式
match(pattern,string[,flags]) 在字符串的开始处匹配模式
split(pattern,string[,maxsplit=0]) 根据模式的匹配项来分割字符串
findall(pattern,string) 列出字符串中模式的所有匹配项
sub(pat,repl,string[,count=0] 将字符串中所有pat的匹配项用repl替换
escape(string) 将字符串中所有特殊正则表达式字符转义

 

 

 

 

 

 

 

 

函数re.compile 将正则表达式转换为模式对象。再用 search和match函数 使用字符串表示的正则表达式,它们会在内部自动转换正则表达式对象。使用re.compile完成一次转换后,每次使用模式的时候,就不用进行转换。

 

函数re.search会在给定字符串寻找第一个匹配。一旦找到MatchObject(True),否则返回None(False).

if re.search(pat,string):
    print 'Found it'

函数re.match会在给定字符串的开头匹配正则表示。

re.match('p','www.python.org') 返回 None

函数re.split 根据匹配项分割字符串

some_text = 'alpha beta.....gamma delta'
print re.split('[. ]+', some_text)

输出

['alpha', 'beta', 'gamma', 'delta']

如果模式包括小括号

print re.split('o(o)', 'foobaooro')

输出

['f', 'o', 'ba', 'o', 'ro']

扩起来的字符组合,会分散在字符串中。

split函数,maxsplit参数表示字符串最多分割的次数:

some_text = 'alpha beta.....gamma delta'
print re.split('[. ]+', some_text, maxsplit = 2)

输出

['alpha', 'beta', 'gamma delta']

函数re.findall 以列表形式返回给定模式的匹配项。

text = 'alpha beta.....gamma delta'
print re.findall('[a-zA-Z]+', text)

输出

['alpha', 'beta', 'gamma', 'delta']

查找特殊符号

text = 'alpha b\eta..--.ga-m---ma delta'
print re.findall(r'[-\\]+', text)

输出

['\\', '--', '-', '---']

函数 re.sub 使用正则来替换字符串

print re.sub('python|jython', 'zjm', 'hello python,jython')

输出

hello zjm,zjm

函数 re.escape 如果字符串很长且包含很多特殊字符,而你又不想输入一堆反斜线的时候。就可以直接用它转义。

pattern = './[]^'
print re.escape(pattern)
print re.escape('www.baidu.com')

输出

\.\/\[\]\^
www\.baidu\.com

在re模块中,很多函数带有flags可选参数。 它是标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。 如 忽略大小写

print re.match('p', 'P1', flags=re.IGNORECASE)

匹配对象和组

组就是放置在圆括号内的子模式。组的序号取决于它左侧的括号数。组的0就是整个模式。 

组中一般包含诸如通配符或重复运算符之类的特殊字符。

m = re.match(r'www\.(.*)\..{3}', 'www.python.org')
print m.group(0)
print m.group(1)
print m.start(1)
print m.end(1)
print m.span(1)

m = re.match('(w{3})', 'www.python.org')
print m.group(1)

输出

www.python.org
python
4
10
(4, 10)
www

作为替换的组号和函数

#coding:utf8

import re

emphasis_pattern = re.compile(r'''
        \*          # 开始 *
        (
        [^\*]*      # 除了*
        )
        \*          # 结束 *
        ''', re.VERBOSE)
m = emphasis_pattern.search('Hello *world*!')
print m.groups()
print re.sub(emphasis_pattern, r'<em>\1</em>', 'Hello *world*!')

输出

('world',)
Hello <em>world</em>!

贪婪模式

emphasis_pattern = re.compile(r'''
        \*          # 开始 *
        (
        (.+)       # 除了*
        )
        \*          # 结束 *
        ''', re.VERBOSE)
m = emphasis_pattern.search('*This* *is* *it*')
print m.groups()
print re.sub(emphasis_pattern, r'<em>\1</em>', '*This* *is* *it*')

输出

('This* *is* *it', 'This* *is* *it')
<em>This* *is* *it</em>

非贪婪模式

只要在重复运算符后面加上问号,就变成非贪婪版本

#coding:utf8

import re

emphasis_pattern = re.compile(r'''
        \*          # 开始 *
        (
        (.+?)       # 除了*
        )
        \*          # 结束 *
        ''', re.VERBOSE)
m = emphasis_pattern.search('*This* *is* *it*')
print m.groups()
print re.sub(emphasis_pattern, r'<em>\1</em>', '*This* *is* *it*')

输出

('This', 'This')
<em>This</em> <em>is</em> <em>it</em>

非贪婪仅会在\*下一个匹配最少的内容。

 

正规则示例

#coding:utf8

import re, fileinput

email_text = """From: foo@bar.baz The Dec 20 01:22:50 2008
From:Foo Fie <foo@bar.baz>
From:Foo Fie2 <foo@bar.baz>
z8888@gmail.com
foo@baz.com"""
email_list = email_text.split('\n')

pat = re.compile(r'[a-z0-9]+@[a-z0-9]+\..{3}', re.IGNORECASE)
addresses = set()
for line in email_list:
    for address in pat.findall(line):
        addresses.add(address)

for address in addresses:
    print address

如果使用的是 fileinput.input 在结束的时候要 加上 fileinput.close.多个文件可以fileinput.nextfile

模板示例

#coding:utf8

import re

text = """the sum of 7 and 9 is [7+9]
[name="Mr.Gumby"] Hello. [name]
"""
text_list = text.split('\n')

pat = re.compile(r'\[(.+?)\]')

scope = {}

def replacement(match):
    code = match.group(1)
    try:
        return str(eval(code, scope))
    except SyntaxError:
        # 执行的赋值语句
        exec code in scope
        return ''

for line in text_list:
    print pat.sub(replacement, line)

输出

the sum of 7 and 9 is 16
 Hello. Mr.Gumby

string模块中已经有非常完美的模板系统了。Template类。

还有其他非常好用的库

functools 为高阶函数提供支持

通过部分参数来使用某个函数(部分求值),再为剩下的参数提供数值。

http://www.cnblogs.com/Security-Darren/p/4168310.html

http://blog.jkey.lu/2013/03/15/python-decorator-and-functools-module/

http://wklken.me/posts/2013/08/18/python-extra-functools.html

difflib  计算机两个序列的相似程序

http://blog.csdn.net/iamaiearner/article/details/9131431

http://www.cnblogs.com/reach296/p/3816387.html

hashlib  为两个不同的字符串计算出签名,确保两个签名完全不同。

http://www.cnblogs.com/the4king/archive/2012/02/06/2340660.html

csv  轻松读写csv文件

http://www.pythonclub.org/python-files/csv

timeit、profile和trace

timeit衡量代码片段运行时间,还可以用time模块代替它。

profile和pstats 可用于代码片段效率的全面分析

trace 提供总的分析 代码哪部分执行,哪部分没执行

datetime 操作日期和时间的类,简单和复杂两种方式都有

主要它的接口更加直观

itertools 创建和联合迭代器

通过重复访问可迭代对象进行循环

logging  日志

提供通用的日志系统

getopt和optparse

命令行解析工具

http://lingxiankong.github.io/blog/2014/01/14/command-line-parser/

cmd

可以编写一个像命令行解释器、跟Python的交互式解释器一样

http://blog.csdn.net/fan_hai_ping/article/details/8435194

 

posted @ 2016-07-27 14:39  笨重的石头  阅读(409)  评论(0)    收藏  举报