python re,random,glob,cgi,marshal模块序列化, Lambda Forms 模块

2024-04-04 13:38

本文主要是介绍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。

  1. print random.uniform(10,20)  
  2. print random.uniform(20,10)  
  3. #---- 结果(不同机器上的结果不一样)  
  4. #18.7356606526  
  5. #12.5798298022  

random.randint

  random.randint()的函数原型为:random.randint(a, b),用于生成一个指定范围内的整数。其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b

  1. print random.randint(12,20)  #生成的随机数n: 12 <= n <= 20  
  2. print random.randint(20,20)  #结果永远是20  
  3. #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的一些例子:

  1. print random.choice("学习Python")   
  2. print random.choice(["JGood","is""a","handsome""boy"])  
  3. print random.choice(("Tuple","List""Dict"))  

random.shuffle

  random.shuffle的函数原型为:random.shuffle(x[, random]),用于将一个列表中的元素打乱。如:

  1. p = ["Python","is""powerful","simple""and so on..."]  
  2. random.shuffle(p)  
  3. print p  
  4. #---- 结果(不同机器上的结果可能不一样。)  
  5. #['powerful', 'simple', 'is', 'Python', 'and so on...']  

random.sample

  random.sample的函数原型为:random.sample(sequence, k),从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列。

  1. list = [12345678910]  
  2. slice = random.sample(list, 5)  #从list中随机获取5个元素,作为一个片断返回  
  3. print slice  
  4. print list #原有序列并没有改变。  

  上面这些方法是random模块中最常用的,在Python手册中,还介绍其他的方法。感兴趣的朋友可以通过查询Python手册了解更详细的信息。


例子:

[python]  view plain copy print ?
  1. import random  
  2. result = random.random()  
  3. print result   #生成0-1的随机数  
  4.   
  5. print random.uniform(10,12)  #10-12的随机数  
  6.   
  7. print random.randint(30,50)  #30-50的随机整数   
  8.   
  9. print random.randrange(10,100,2#从10开始到100结束,步长为2的序列中,随机选一个  
  10.   
  11. list = [1,2,5,6,7,8,8]  
  12. print random.choice(list)   #从序列中随机选一个  
  13.   
  14.   
  15.   
  16. random.shuffle(list)     #重新排列序列  
  17. print list  
  18.   
  19. list = [12345678910]     
  20. slice = random.sample(list, 5)   #从序列中取样  
  21. 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.gif2.txt, and card.gifglob() 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']

上代码:

[python]  view plain copy print ?
  1. import glob  
  2. fileList = glob.glob(r'c:\*.txt')  
  3. print fileList  
  4. for file_name in fileList:  
  5.     print file_name  
  6.   
  7. print '*'*40  
  8. fileGen = glob.iglob(r'c:\*.txt')  
  9. print fileGen  
  10. for filename in fileGen:  
  11.     print filename  

结果:

[python]  view plain copy print ?
  1. ['c:\\1.txt''c:\\adf.txt''c:\\baidu.txt''c:\\resultURL.txt']  
  2. c:\1.txt  
  3. c:\adf.txt  
  4. c:\baidu.txt  
  5. c:\resultURL.txt  
  6. ****************************************  
  7. <generator object iglob at 0x01DC1E90>  
  8. c:\1.txt  
  9. c:\adf.txt  
  10. c:\baidu.txt  
  11. c:\resultURL.txt  

上代码:

[python]  view plain copy print ?
  1. import marshal  
  2. data1 = ['abc',12,23]    #几个测试数据  
  3. data2 = {1:'aaa',"b":'dad'}  
  4. data3 = (1,2,4)  
  5.   
  6.   
  7. output_file = open("a.txt",'wb')<span style="white-space:pre">  </span>#把这些数据序列化到文件中,<span style="color:#ff0000;"><strong>注:文件必须以二进制模式打开</strong></span>  
  8. marshal.dump(data1,output_file)  
  9. marshal.dump(data2,output_file)  
  10. marshal.dump(data3,output_file)  
  11. output_file.close()  
  12.   
  13.   
  14. input_file = open('a.txt','rb')<span style="white-space:pre">       </span>#从文件中读取序列化的数据  
  15. #data1 = []  
  16. data1 = marshal.load(input_file)  
  17. data2 = marshal.load(input_file)  
  18. data3 = marshal.load(input_file)  
  19. print data1<span style="white-space:pre">               </span>#给同志们打印出结果看看  
  20. print data2  
  21. print data3  
  22.   
  23.   
  24. outstring = marshal.dumps(data1)<span style="white-space:pre">  </span>#marshal.dumps()返回是一个字节串,该字节串用于写入文件  
  25. open('out.txt','wb').write(outstring)  
  26.   
  27.   
  28. file_data = open('out.txt','rb').read()  
  29. real_data = marshal.loads(file_data)  
  30. print real_data  

结果:

[python]  view plain copy print ?
  1. ['abc'1223]  
  2. {1'aaa''b''dad'}  
  3. (124)  
  4. ['abc'1223]  

############################################

debian:/usr/local/web/apache/cgi-bin# cat test.py 
#!/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();

输出如下:
debian:/usr/local/web/apache/cgi-bin# curl -d "a=1&b=2&c=3&c=4" localhost/test.py
Hello World!
cgi.FieldStorage()
FieldStorage(None, None, [MiniFieldStorage('a', '1'), MiniFieldStorage('b', '2'), MiniFieldStorage('c', '3'), MiniFieldStorage('c', '4')])
a: 1 b: 2
c1: ['3', '4']
c2: ['3', '4']
This user is requesting more than one item
c3: 3
cgi.print_environ_usage()

<H3>These environment variables could have been set:</H3>
<UL>
<LI>AUTH_TYPE
<LI>CONTENT_LENGTH
<LI>CONTENT_TYPE
<LI>DATE_GMT
<LI>DATE_LOCAL
<LI>DOCUMENT_NAME
<LI>DOCUMENT_ROOT
<LI>DOCUMENT_URI
<LI>GATEWAY_INTERFACE
<LI>LAST_MODIFIED
<LI>PATH
<LI>PATH_INFO
<LI>PATH_TRANSLATED
<LI>QUERY_STRING
<LI>REMOTE_ADDR
<LI>REMOTE_HOST
<LI>REMOTE_IDENT
<LI>REMOTE_USER
<LI>REQUEST_METHOD
<LI>SCRIPT_NAME
<LI>SERVER_NAME
<LI>SERVER_PORT
<LI>SERVER_PROTOCOL
<LI>SERVER_ROOT
<LI>SERVER_SOFTWARE
</UL>
In addition, HTTP headers sent by the server may be passed in the
environment as well.  Here are some common variable names:
<UL>
<LI>HTTP_ACCEPT
<LI>HTTP_CONNECTION
<LI>HTTP_HOST
<LI>HTTP_PRAGMA
<LI>HTTP_REFERER
<LI>HTTP_USER_AGENT
</UL>

cgi.print_form()

延伸阅读:
http://www.cnblogs.com/melorain/articles/713033.html

############################################

marshel模块的几个函数:

The module defines these functions:

marshal. dump ( valuefile [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 EOFErrorValueError 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  EOFErrorValueError 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就熟练了。。

>>> def make_incrementor(n):
...     return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43


原创文章请注明转载自 老王python ,本文地址: http://www.cnpythoner.com/post/95.html

这篇关于python re,random,glob,cgi,marshal模块序列化, Lambda Forms 模块的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/875922

相关文章

一文教你使用Python实现本地分页

《一文教你使用Python实现本地分页》这篇文章主要为大家详细介绍了Python如何实现本地分页的算法,主要针对二级数据结构,文中的示例代码简洁易懂,有需要的小伙伴可以了解下... 在项目开发的过程中,遇到分页的第一页就展示大量的数据,导致前端列表加载展示的速度慢,所以需要在本地加入分页处理,把所有数据先放

树莓派启动python的实现方法

《树莓派启动python的实现方法》本文主要介绍了树莓派启动python的实现方法,文中通过图文介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录一、RASPBerry系统设置二、使用sandroidsh连接上开发板Raspberry Pi三、运

Python给Excel写入数据的四种方法小结

《Python给Excel写入数据的四种方法小结》本文主要介绍了Python给Excel写入数据的四种方法小结,包含openpyxl库、xlsxwriter库、pandas库和win32com库,具有... 目录1. 使用 openpyxl 库2. 使用 xlsxwriter 库3. 使用 pandas 库

python实现简易SSL的项目实践

《python实现简易SSL的项目实践》本文主要介绍了python实现简易SSL的项目实践,包括CA.py、server.py和client.py三个模块,文中通过示例代码介绍的非常详细,对大家的学习... 目录运行环境运行前准备程序实现与流程说明运行截图代码CA.pyclient.pyserver.py参

使用Python实现批量分割PDF文件

《使用Python实现批量分割PDF文件》这篇文章主要为大家详细介绍了如何使用Python进行批量分割PDF文件功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、架构设计二、代码实现三、批量分割PDF文件四、总结本文将介绍如何使用python进js行批量分割PDF文件的方法

Python实现多路视频多窗口播放功能

《Python实现多路视频多窗口播放功能》这篇文章主要为大家详细介绍了Python实现多路视频多窗口播放功能的相关知识,文中的示例代码讲解详细,有需要的小伙伴可以跟随小编一起学习一下... 目录一、python实现多路视频播放功能二、代码实现三、打包代码实现总结一、python实现多路视频播放功能服务端开

使用Python在Excel中创建和取消数据分组

《使用Python在Excel中创建和取消数据分组》Excel中的分组是一种通过添加层级结构将相邻行或列组织在一起的功能,当分组完成后,用户可以通过折叠或展开数据组来简化数据视图,这篇博客将介绍如何使... 目录引言使用工具python在Excel中创建行和列分组Python在Excel中创建嵌套分组Pyt

Python实现视频转换为音频的方法详解

《Python实现视频转换为音频的方法详解》这篇文章主要为大家详细Python如何将视频转换为音频并将音频文件保存到特定文件夹下,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. python需求的任务2. Python代码的实现3. 代码修改的位置4. 运行结果5. 注意事项

Python利用自带模块实现屏幕像素高效操作

《Python利用自带模块实现屏幕像素高效操作》这篇文章主要为大家详细介绍了Python如何利用自带模块实现屏幕像素高效操作,文中的示例代码讲解详,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1、获取屏幕放缩比例2、获取屏幕指定坐标处像素颜色3、一个简单的使用案例4、总结1、获取屏幕放缩比例from

使用Python在Excel中插入、修改、提取和删除超链接

《使用Python在Excel中插入、修改、提取和删除超链接》超链接是Excel中的常用功能,通过点击超链接可以快速跳转到外部网站、本地文件或工作表中的特定单元格,有效提升数据访问的效率和用户体验,这... 目录引言使用工具python在Excel中插入超链接Python修改Excel中的超链接Python