Python基础之【第四篇】
2015-11-23 14:07
561 查看
Python 模块
为了实现对程序特定功能的调用和存储,人们将代码封装起来,可以供其他程序调用,可以称之为模块.如:os 是系统相关的模块;file是文件操作相关的模块;sys是访问python解释器的变量和函数的方法的模块等...
模块分为三种:
自定义模块
内置模块
第三方模块
import subprocess obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out_error_list = obj.communicate('print "hello"') print out_error_list
View Code
random模块
Python中的random模块用于生成随机数。下面介绍一下random模块中最常用的几个函数。
random.random() #random.random()用于生成一个0到1的随机符点数: 0 <= n < 1.0 例如: >>> random.random() 0.085891554608514942 random.randint() random.randint()的函数原型为:random.randint(a, b),用于生成一个指定范围内的整数。其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b >>> random.randint(1,100) 76 random.randrange random.randrange的函数原型为:random.randrange([start], stop[, step]),从指定范围内,按指定基数递增的集合中 获取一个随机数。 如:random.randrange(10, 100, 2),结果相当于从[10, 12, 14, 16, ... 96, 98]序列中获取一个随机数 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.choice('qiwsir.github.io') 'g' 多个字符中选取特定数量的字符: random.sample('qiwsir.github.io',3) ['w', 's', 'b'] 随机选取字符串: random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] ) 洗牌:把原有的顺序打乱,按照随机顺序排列 >>> items = [1, 2, 3, 4, 5, 6] >>> random.shuffle(items) >>> items [3, 2, 5, 6, 4, 1]
随机验证码实例:
import random checkcode = '' #定义一个空字符串 for i in range(4): #在[0, 1, 2, 3]中进行循环 current = random.randrange(0,4) if current != i: temp = chr(random.randint(65,90)) else: temp = random.randint(0,9) checkcode += str(temp) print checkcode
logging模块:
用于便捷记录日志且线程安全的模块
import logging logging.basicConfig(filename='log.log', #通过logging.basicConfig函数对日志的输出格式及方式做相关配置 format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S %p', level=10) logging.debug('debug') logging.info('info') logging.warning('warning') logging.error('error') logging.critical('critical') logging.log(10,'log') ############################################### 日志等级: 日志级别大小关系为:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET,当然也可以自己定义日志级别。 1 CRITICAL = 50 2 FATAL = CRITICAL ERROR = 40 WARNING = 30 5 WARN = WARNING 6 INFO = 20 7 DEBUG = 10 NOTSET = 0
将日志同时输出到文件和屏幕:
import logging #创建一个logger 3 logger = logging.getLogger('logger') #name名称 4 logger.setLevel(logging.DEBUG) #全局日志级别 #创建一个handler,用于写入日志文件 6 fh = logging.FileHandler('test.log') #输出到日志文件test.log 7 fh.setLevel(logging.DEBUG) #debug级别以上的日志信息全部输出到文件test.log中 #再创建一个handler,用于输出到控制台 ch = logging.StreamHandler() #输出屏幕 ch.setLevel(logging.ERROR) #error级别以上的日志全部输出到屏幕 #定义handler的输出格式 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) fh.setFormatter(formatter) #给logger添加handler logger.addHandler(ch) #把屏幕和文件句柄交给logger接口执行 logger.addHandler(fh) # 'application' code logger.debug('debug message') logger.info('info message') logger.warn('warn message') logger.error('error message') logger.critical('critical message')
Python 正则表达式之 re模块:
Python中有关正则表达式的知识和语法,不作过多解释,网上有许多学习的资料。这里主要介绍Python中常用的正则表达式处理函数。
re.match
re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配不成功的话,match()就返回none。
re.match(pattern, string, flags=0)
import re m = re.match(r'www','www.baidu.com') #只匹配首行开头的字符. print m.group() #返回被www 匹配的字符串
re.search
re.search 扫描整个字符串并返回第一个成功的匹配,如果字符串没有匹配,则返回None。
import re obj = re.search('\d+', 'u123uu888asf') #'d+'表示以数字进行分割. if obj: print obj.group()
re.match与re.search的区别:re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。
re.sub
re.sub函数进行以正则表达式为基础的替换工作
import re text = "123abc456def789" #text = re.sub('\d+', 'QQ', text) #匹配任何十进制(\d+),并将其替换为QQ text = re.sub('\d+', 'BB', text, 1) #匹配任何十进制数字,并将第一次出现的替换为QQ print text
re.split
可以使用re.split根据指定匹配进行分割,示例如下.
content = "'1+2*(3+4)(7+8)*10/2+5'" #li = re.split('\*', content) #以*号对content进行分割. li = re.split('\*', content, 1) print li
re.findall
上述re.match和re.search均用于匹配单值,即:只能匹配字符串中的一个,如果想要匹配到字符串中所有符合条件的元素,则需要使用 findall。
import re text = "fa123uu888asfabc456def789" obj = re.findall('\d+', text) print obj ##################################### ['123', '888', '456', '789']
re.compile
可以把那些经常使用的正则表达式编译成正则表达式对象,再次使用时不用再编译,这样可以提高一定的效率.
import re text = "JGood is a handsome boy, he is cool, clever, and so on..." regex = re.compile(r'\w*oo\w*') print regex.findall(text) #查找所有包含'oo'的单词 print regex.sub(lambda m: '[' + m.group(0) + ']', text) #将字符串中含有'oo'的单词用[]括起来. ##############################################################结果如下. ['JGood', 'cool'] [JGood] is a handsome boy, he is [cool], clever, and so on...
Python预定义字符集如下:
字符: . 匹配除换行符以外的任意字符 \w 匹配字母或数字或下划线或汉字 \s 匹配任意的空白符 \d 匹配数字 \b 匹配单词的开始或结束 ^ 匹配字符串的开始 $ 匹配字符串的结束 次数: * 重复零次或更多次 + 重复一次或更多次 ? 重复零次或一次 {n} 重复n次 {n,} 重复n次或更多次 {n,m} 重复n到m次
相关文章推荐
- python codeforces 322 div2 C
- Python问题汇总
- PYTHON之全局变量
- Python如何使用tfidf
- [LeetCode]题解(python):060-Permutation Sequence
- [LeetCode]题解(python):059-Spiral Matrix II
- python 里关于字符的处理
- python 开发中易混淆点
- [LeetCode]题解(python):058-Length of Last Word
- python实现爬虫统计学校BBS男女比例(三)数据处理
- python统计小脚本
- 学习python地址
- Python - 操作Excel(上)
- 通过矩阵求两个向量集中元素两两之间的欧氏距离(python实现)
- 使用python来访问Hadoop HDFS存储实现文件的操作
- python django 快速搭建blog
- [python]help 函数
- <LeetCode><Medium> 3 Longest Substring Without Repeating Characters
- Python之删除代码中空白行
- selenium python (一) 开发环境搭建