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删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

Python办公自动化实战之打造智能邮件发送工具

《Python办公自动化实战之打造智能邮件发送工具》在数字化办公场景中,邮件自动化是提升工作效率的关键技能,本文将演示如何使用Python的smtplib和email库构建一个支持图文混排,多附件,多... 目录前言一、基础配置:搭建邮件发送框架1.1 邮箱服务准备1.2 核心库导入1.3 基础发送函数二、

Python包管理工具pip的升级指南

《Python包管理工具pip的升级指南》本文全面探讨Python包管理工具pip的升级策略,从基础升级方法到高级技巧,涵盖不同操作系统环境下的最佳实践,我们将深入分析pip的工作原理,介绍多种升级方... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

基于Python实现一个图片拆分工具

《基于Python实现一个图片拆分工具》这篇文章主要为大家详细介绍了如何基于Python实现一个图片拆分工具,可以根据需要的行数和列数进行拆分,感兴趣的小伙伴可以跟随小编一起学习一下... 简单介绍先自己选择输入的图片,默认是输出到项目文件夹中,可以自己选择其他的文件夹,选择需要拆分的行数和列数,可以通过

Python中反转字符串的常见方法小结

《Python中反转字符串的常见方法小结》在Python中,字符串对象没有内置的反转方法,然而,在实际开发中,我们经常会遇到需要反转字符串的场景,比如处理回文字符串、文本加密等,因此,掌握如何在Pyt... 目录python中反转字符串的方法技术背景实现步骤1. 使用切片2. 使用 reversed() 函

Python中将嵌套列表扁平化的多种实现方法

《Python中将嵌套列表扁平化的多种实现方法》在Python编程中,我们常常会遇到需要将嵌套列表(即列表中包含列表)转换为一个一维的扁平列表的需求,本文将给大家介绍了多种实现这一目标的方法,需要的朋... 目录python中将嵌套列表扁平化的方法技术背景实现步骤1. 使用嵌套列表推导式2. 使用itert

使用Docker构建Python Flask程序的详细教程

《使用Docker构建PythonFlask程序的详细教程》在当今的软件开发领域,容器化技术正变得越来越流行,而Docker无疑是其中的佼佼者,本文我们就来聊聊如何使用Docker构建一个简单的Py... 目录引言一、准备工作二、创建 Flask 应用程序三、创建 dockerfile四、构建 Docker

Python使用vllm处理多模态数据的预处理技巧

《Python使用vllm处理多模态数据的预处理技巧》本文深入探讨了在Python环境下使用vLLM处理多模态数据的预处理技巧,我们将从基础概念出发,详细讲解文本、图像、音频等多模态数据的预处理方法,... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核