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

相关文章

VSCode配置Anaconda Python环境的实现

《VSCode配置AnacondaPython环境的实现》VisualStudioCode中可以使用Anaconda环境进行Python开发,本文主要介绍了VSCode配置AnacondaPytho... 目录前言一、安装 Visual Studio Code 和 Anaconda二、创建或激活 conda

pytorch+torchvision+python版本对应及环境安装

《pytorch+torchvision+python版本对应及环境安装》本文主要介绍了pytorch+torchvision+python版本对应及环境安装,安装过程中需要注意Numpy版本的降级,... 目录一、版本对应二、安装命令(pip)1. 版本2. 安装全过程3. 命令相关解释参考文章一、版本对

讯飞webapi语音识别接口调用示例代码(python)

《讯飞webapi语音识别接口调用示例代码(python)》:本文主要介绍如何使用Python3调用讯飞WebAPI语音识别接口,重点解决了在处理语音识别结果时判断是否为最后一帧的问题,通过运行代... 目录前言一、环境二、引入库三、代码实例四、运行结果五、总结前言基于python3 讯飞webAPI语音

基于Python开发PDF转PNG的可视化工具

《基于Python开发PDF转PNG的可视化工具》在数字文档处理领域,PDF到图像格式的转换是常见需求,本文介绍如何利用Python的PyMuPDF库和Tkinter框架开发一个带图形界面的PDF转P... 目录一、引言二、功能特性三、技术架构1. 技术栈组成2. 系统架构javascript设计3.效果图

Python如何在Word中生成多种不同类型的图表

《Python如何在Word中生成多种不同类型的图表》Word文档中插入图表不仅能直观呈现数据,还能提升文档的可读性和专业性,本文将介绍如何使用Python在Word文档中创建和自定义各种图表,需要的... 目录在Word中创建柱形图在Word中创建条形图在Word中创建折线图在Word中创建饼图在Word

Python Excel实现自动添加编号

《PythonExcel实现自动添加编号》这篇文章主要为大家详细介绍了如何使用Python在Excel中实现自动添加编号效果,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1、背景介绍2、库的安装3、核心代码4、完整代码1、背景介绍简单的说,就是在Excel中有一列h=会有重复

Python FastAPI入门安装使用

《PythonFastAPI入门安装使用》FastAPI是一个现代、快速的PythonWeb框架,用于构建API,它基于Python3.6+的类型提示特性,使得代码更加简洁且易于绶护,这篇文章主要介... 目录第一节:FastAPI入门一、FastAPI框架介绍什么是ASGI服务(WSGI)二、FastAP

Python中Windows和macOS文件路径格式不一致的解决方法

《Python中Windows和macOS文件路径格式不一致的解决方法》在Python中,Windows和macOS的文件路径字符串格式不一致主要体现在路径分隔符上,这种差异可能导致跨平台代码在处理文... 目录方法 1:使用 os.path 模块方法 2:使用 pathlib 模块(推荐)方法 3:统一使

一文教你解决Python不支持中文路径的问题

《一文教你解决Python不支持中文路径的问题》Python是一种广泛使用的高级编程语言,然而在处理包含中文字符的文件路径时,Python有时会表现出一些不友好的行为,下面小编就来为大家介绍一下具体的... 目录问题背景解决方案1. 设置正确的文件编码2. 使用pathlib模块3. 转换路径为Unicod

Python结合Flask框架构建一个简易的远程控制系统

《Python结合Flask框架构建一个简易的远程控制系统》这篇文章主要为大家详细介绍了如何使用Python与Flask框架构建一个简易的远程控制系统,能够远程执行操作命令(如关机、重启、锁屏等),还... 目录1.概述2.功能使用系统命令执行实时屏幕监控3. BUG修复过程1. Authorization