本文主要是介绍python re,random,glob,cgi,marshal模块序列化, Lambda Forms 模块,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
import re
#
match_object = re.match('foo','foo')
if match_object is not None:print type(match_object)print match_object.group()#
match_object = re.match('foo','fooabv')
if match_object is not None:print match_object.group()#match从头开始匹配
match_object = re.match('foo','afooabv')
if match_object is not None:print match_object.group()
else:print 'not match'#利用面向对象的特点,一行完成
print re.match('love','lovesomebody is a happy thing').group()#与match的区别:match从头开始匹配,search是查找
match_object = re.search('foo','afooabv')
if match_object is not None:print match_object.group()
else:print 'not match'#|的使用
bt = 'bat|bit|bot'
match_object = re.match(bt,'batsdf')
if match_object is not None:print "|...|" + match_object.group()#会匹配成功
else:print 'not match'bt = 'bat|bit|bot'
match_object = re.search(bt,'aabatsdf')
if match_object is not None:print "|search|" + match_object.group()#会匹配成功,如果用match就不会匹配成功
else:print 'not match'
###########################################################
Python中的random模块用于生成随机数。下面介绍一下random模块中最常用的几个函数。
random.random
random.random()用于生成一个0到1的随机符点数: 0 <= n < 1.0
random.uniform
random.uniform的函数原型为:random.uniform(a, b),用于生成一个指定范围内的随机符点数,两个参数其中一个是上限,一个是下限。如果a > b,则生成的随机数n: a <= n <= b。如果 a <b, 则 b <= n <= a。
- print random.uniform(10,20)
- print random.uniform(20,10)
- #---- 结果(不同机器上的结果不一样)
- #18.7356606526
- #12.5798298022
random.randint
random.randint()的函数原型为:random.randint(a, b),用于生成一个指定范围内的整数。其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b
- print random.randint(12,20) #生成的随机数n: 12 <= n <= 20
- print random.randint(20,20) #结果永远是20
- #print random.randint(20, 10) #该语句是错误的。下限必须小于上限。
random.randrange
random.randrange的函数原型为:random.randrange([start], stop[, step]),从指定范围内,按指定基数递增的集合中 获取一个随机数。如:random.randrange(10, 100, 2),结果相当于从[10, 12, 14, 16, ... 96, 98]序列中获取一个随机数。random.randrange(10, 100, 2)在结果上与 random.choice(range(10, 100, 2) 等效。
random.choice
random.choice从序列中获取一个随机元素。其函数原型为:random.choice(sequence)。参数sequence表示一个有序类型。这里要说明 一下:sequence在python不是一种特定的类型,而是泛指一系列的类型。list, tuple, 字符串都属于sequence。有关sequence可以查看python手册数据模型这一章,也可以参考:http://www.17xie.com/read-37422.html 。下面是使用choice的一些例子:
- print random.choice("学习Python")
- print random.choice(["JGood","is", "a","handsome", "boy"])
- print random.choice(("Tuple","List", "Dict"))
random.shuffle
random.shuffle的函数原型为:random.shuffle(x[, random]),用于将一个列表中的元素打乱。如:
- p = ["Python","is", "powerful","simple", "and so on..."]
- random.shuffle(p)
- print p
- #---- 结果(不同机器上的结果可能不一样。)
- #['powerful', 'simple', 'is', 'Python', 'and so on...']
random.sample
random.sample的函数原型为:random.sample(sequence, k),从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列。
- list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- slice = random.sample(list, 5) #从list中随机获取5个元素,作为一个片断返回
- print slice
- print list #原有序列并没有改变。
上面这些方法是random模块中最常用的,在Python手册中,还介绍其他的方法。感兴趣的朋友可以通过查询Python手册了解更详细的信息。
例子:
- import random
- result = random.random()
- print result #生成0-1的随机数
- print random.uniform(10,12) #10-12的随机数
- print random.randint(30,50) #30-50的随机整数
- print random.randrange(10,100,2) #从10开始到100结束,步长为2的序列中,随机选一个
- list = [1,2,5,6,7,8,8]
- print random.choice(list) #从序列中随机选一个
- random.shuffle(list) #重新排列序列
- print list
- list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- slice = random.sample(list, 5) #从序列中取样
- print slice
0.782366976492
11.5582702631
42
88
7
[1, 5, 8, 6, 7, 2, 8]
[10, 2, 9, 7, 8]
######################################################
glob是python自己带的一个文件操作相关模块,用它可以查找符合自己目的的文件,就类似于Windows下的文件搜索,支持通配符操作,*,?,[]这三个通配符,*代表0个或多个字符,?代表一个字符,[]匹配指定范围内的字符,如[0-9]匹配数字。
它的主要方法就是glob,该方法返回所有匹配的文件路径列表,该方法需要一个参数用来指定匹配的路径字符串(本字符串可以为绝对路径也可以为相对路径),其返回的文件名只包括当前目录里的文件名,不包括子文件夹里的文件。
python手机中的介绍:
The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell. No tilde expansion is done, but *, ?, and character ranges expressed with [] will be correctly matched. This is done by using the os.listdir() and fnmatch.fnmatch() functions in concert, and not by actually invoking a subshell. (For tilde and shell variable expansion, use os.path.expanduser() and os.path.expandvars().)
- glob. glob ( pathname ) #返回列表
- Return a possibly-empty list of path names that match pathname, which must be a string containing a path specification. pathname can be either absolute (like /usr/src/Python-1.5/Makefile) or relative (like ../../Tools/*/*.gif), and can contain shell-style wildcards. Broken symlinks are included in the results (as in the shell).
- glob. iglob ( pathname ) #返回迭代器
-
Return an iterator which yields the same values as glob() without actually storing them all simultaneously.
New in version 2.5.
For example, consider a directory containing only the following files: 1.gif, 2.txt, and card.gif. glob() will produce the following results. Notice how any leading components of the path are preserved.
>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
上代码:
- import glob
- fileList = glob.glob(r'c:\*.txt')
- print fileList
- for file_name in fileList:
- print file_name
- print '*'*40
- fileGen = glob.iglob(r'c:\*.txt')
- print fileGen
- for filename in fileGen:
- print filename
结果:
- ['c:\\1.txt', 'c:\\adf.txt', 'c:\\baidu.txt', 'c:\\resultURL.txt']
- c:\1.txt
- c:\adf.txt
- c:\baidu.txt
- c:\resultURL.txt
- ****************************************
- <generator object iglob at 0x01DC1E90>
- c:\1.txt
- c:\adf.txt
- c:\baidu.txt
- c:\resultURL.txt
上代码:
- import marshal
- data1 = ['abc',12,23] #几个测试数据
- data2 = {1:'aaa',"b":'dad'}
- data3 = (1,2,4)
- output_file = open("a.txt",'wb')<span style="white-space:pre"> </span>#把这些数据序列化到文件中,<span style="color:#ff0000;"><strong>注:文件必须以二进制模式打开</strong></span>
- marshal.dump(data1,output_file)
- marshal.dump(data2,output_file)
- marshal.dump(data3,output_file)
- output_file.close()
- input_file = open('a.txt','rb')<span style="white-space:pre"> </span>#从文件中读取序列化的数据
- #data1 = []
- data1 = marshal.load(input_file)
- data2 = marshal.load(input_file)
- data3 = marshal.load(input_file)
- print data1<span style="white-space:pre"> </span>#给同志们打印出结果看看
- print data2
- print data3
- outstring = marshal.dumps(data1)<span style="white-space:pre"> </span>#marshal.dumps()返回是一个字节串,该字节串用于写入文件
- open('out.txt','wb').write(outstring)
- file_data = open('out.txt','rb').read()
- real_data = marshal.loads(file_data)
- print real_data
结果:
- ['abc', 12, 23]
- {1: 'aaa', 'b': 'dad'}
- (1, 2, 4)
- ['abc', 12, 23]
############################################
#!/usr/bin/pythonimport cgi
import sysprint "Content-type: text/html\r\n"
print "Hello World!"form = cgi.FieldStorage()
print 'cgi.FieldStorage()'
print form#form is a list
if 'a' not in form or 'b' not in form:print 'Error'print 'Please fill in the a and b.'sys.exit();print 'a:', form['a'].value, 'b:', form['b'].value'''
form.getlist is a list
'''
print 'c1:', form.getlist('c')c = form.getvalue('c')
print 'c2:', c
if isinstance(c, list):#c=3&c=4,参数c对应多个值print 'This user is requesting more than one item'
else:#c=3, 参数c只有一个值print 'This user is requesting only one item''''
c=3&c=4, the result is 3, c=4&c=3, the result is 4, 如果c有一个或多个值,只取第1个值
'''
c = form.getfirst('c')
print 'c3:', cprint 'cgi.print_environ_usage()'
cgi.print_environ_usage()print 'cgi.print_form()'
cgi.print_form()print 'cgi.test()'
cgi.test();
############################################
marshel模块的几个函数:
The module defines these functions:
- marshal. dump ( value, file [, version ] )
-
Write the value on the open file. The value must be a supported type. The file must be an open file object such as sys.stdout or returned by open() oros.popen(). It must be opened in binary mode ('wb' or 'w+b').
If the value has (or contains an object that has) an unsupported type, a ValueError exception is raised — but garbage data will also be written to the file. The object will not be properly read back by load().
New in version 2.4: The version argument indicates the data format that dump should use (see below).
- marshal. load ( file )
-
Read one value from the open file and return it. If no valid value is read (e.g. because the data has a different Python version’s incompatible marshal format), raise EOFError, ValueError or TypeError. The file must be an open file object opened in binary mode ('rb' or 'r+b').
Warning
If an object containing an unsupported type was marshalled with dump(), load() will substitute None for the unmarshallable type.
- marshal. dumps ( value [, version ] )
-
Return the string that would be written to a file by dump(value, file). The value must be a supported type. Raise a ValueError exception if value has (or contains an object that has) an unsupported type.
New in version 2.4: The version argument indicates the data format that dumps should use (see below).
- marshal. loads ( string )
- Convert the string to a value. If no valid value is found, raise EOFError, ValueError or TypeError. Extra characters in the string are ignored.
In addition, the following constants are defined:
- marshal. version
-
Indicates the format that the module uses.
marshal.version的用处:marshal不保证不同的python版本之间的兼容性,所以保留个版本信息的函数...
#################################################
python lambda是在python中使用lambda来创建匿名函数,而用def创建的方法是有名称的,除了从表面上的方法名不一样外,python lambda还有哪些和def不一样呢?
1 python lambda会创建一个函数对象,但不会把这个函数对象赋给一个标识符,而def则会把函数对象赋值给一个变量。
2 python lambda它只是一个表达式,而def则是一个语句。
下面是python lambda的格式,看起来好精简阿。
lambda x: print x
如果你在python 列表解析里用到python lambda,我感觉意义不是很大,因为python lambda它会创建一个函数对象,但马上又给丢弃了,因为你没有使用它的返回值,即那个函数对象。也正是由于lambda只是一个表达式,它可以直接作为python 列表或python 字典的成员,比如:
info = [lamba a: a**3, lambda b: b**3]
在这个地方没有办法用def语句直接代替。因为def是语句,不是表达式不能嵌套在里面,lambda表达式在“:”后只能有一个表达式。也就是说,在def中,用return可以返回的也可以放在lambda后面,不能用return返回的也不能定义在python lambda后面。因此,像if或for或print这种语句就不能用于lambda中,lambda一般只用来定义简单的函数。
下面举几个python lambda的例子吧
1单个参数的:
g = lambda x:x*2
print g(3)
结果是6
2多个参数的:
m = lambda x,y,z: (x-y)*z
print m(3,1,2)
结果是4
没事写程序的时候多用用python lambda就熟练了。。
原创文章请注明转载自 老王python ,本文地址: http://www.cnpythoner.com/post/95.html
这篇关于python re,random,glob,cgi,marshal模块序列化, Lambda Forms 模块的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!