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结合PyWebView库打造跨平台桌面应用

《Python结合PyWebView库打造跨平台桌面应用》随着Web技术的发展,将HTML/CSS/JavaScript与Python结合构建桌面应用成为可能,本文将系统讲解如何使用PyWebView... 目录一、技术原理与优势分析1.1 架构原理1.2 核心优势二、开发环境搭建2.1 安装依赖2.2 验

一文详解如何在Python中从字符串中提取部分内容

《一文详解如何在Python中从字符串中提取部分内容》:本文主要介绍如何在Python中从字符串中提取部分内容的相关资料,包括使用正则表达式、Pyparsing库、AST(抽象语法树)、字符串操作... 目录前言解决方案方法一:使用正则表达式方法二:使用 Pyparsing方法三:使用 AST方法四:使用字

Python列表去重的4种核心方法与实战指南详解

《Python列表去重的4种核心方法与实战指南详解》在Python开发中,处理列表数据时经常需要去除重复元素,本文将详细介绍4种最实用的列表去重方法,有需要的小伙伴可以根据自己的需要进行选择... 目录方法1:集合(set)去重法(最快速)方法2:顺序遍历法(保持顺序)方法3:副本删除法(原地修改)方法4:

Python运行中频繁出现Restart提示的解决办法

《Python运行中频繁出现Restart提示的解决办法》在编程的世界里,遇到各种奇怪的问题是家常便饭,但是,当你的Python程序在运行过程中频繁出现“Restart”提示时,这可能不仅仅是令人头疼... 目录问题描述代码示例无限循环递归调用内存泄漏解决方案1. 检查代码逻辑无限循环递归调用内存泄漏2.

Python中判断对象是否为空的方法

《Python中判断对象是否为空的方法》在Python开发中,判断对象是否为“空”是高频操作,但看似简单的需求却暗藏玄机,从None到空容器,从零值到自定义对象的“假值”状态,不同场景下的“空”需要精... 目录一、python中的“空”值体系二、精准判定方法对比三、常见误区解析四、进阶处理技巧五、性能优化

使用Python构建一个Hexo博客发布工具

《使用Python构建一个Hexo博客发布工具》虽然Hexo的命令行工具非常强大,但对于日常的博客撰写和发布过程,我总觉得缺少一个直观的图形界面来简化操作,下面我们就来看看如何使用Python构建一个... 目录引言Hexo博客系统简介设计需求技术选择代码实现主框架界面设计核心功能实现1. 发布文章2. 加

python logging模块详解及其日志定时清理方式

《pythonlogging模块详解及其日志定时清理方式》:本文主要介绍pythonlogging模块详解及其日志定时清理方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录python logging模块及日志定时清理1.创建logger对象2.logging.basicCo

Python如何自动生成环境依赖包requirements

《Python如何自动生成环境依赖包requirements》:本文主要介绍Python如何自动生成环境依赖包requirements问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑... 目录生成当前 python 环境 安装的所有依赖包1、命令2、常见问题只生成当前 项目 的所有依赖包1、

如何将Python彻底卸载的三种方法

《如何将Python彻底卸载的三种方法》通常我们在一些软件的使用上有碰壁,第一反应就是卸载重装,所以有小伙伴就问我Python怎么卸载才能彻底卸载干净,今天这篇文章,小编就来教大家如何彻底卸载Pyth... 目录软件卸载①方法:②方法:③方法:清理相关文件夹软件卸载①方法:首先,在安装python时,下

python uv包管理小结

《pythonuv包管理小结》uv是一个高性能的Python包管理工具,它不仅能够高效地处理包管理和依赖解析,还提供了对Python版本管理的支持,本文主要介绍了pythonuv包管理小结,具有一... 目录安装 uv使用 uv 管理 python 版本安装指定版本的 Python查看已安装的 Python