首页 > 其他 > 详细

常用模块

时间:2017-10-28 12:06:33      阅读:207      评论:0      收藏:0      [点我收藏+]

一.re模块

  1.正则

  正则就是用一些特殊含义的符号组合到一起(称为正则表达式)来描述字符或者字符串的方法。或者说:正则就是藐视一类事物的规则。

  在Python中,它内嵌在Python中,并通过re模块实现。正则表达式模式被编译成一系列的字节码,然后由用C编写的匹配引擎执行。

  2.常用匹配模式

#\w 匹配字母数字下划线
print(re.findall(‘\w‘,‘alex say hello alex sb 123_ %*‘))
#\W 匹配非字母数字下划线
print(re.findall(‘\W‘,‘alex say hello alex sb 123_ %*‘))
#\s匹配任意空白字符[\t\n\r\f]
print(re.findall(‘\s‘,‘alex say he\n \tllo alex sb 123_ %*‘))
#\S匹配任意非空字符
print(re.findall(‘\S‘,‘alex say he\n \tllo alex sb 123_ %*‘))
#\D匹配非数字
print(re.findall(‘\D‘,‘alex say he\n \tllo alex sb 123_ %‘))
#\A寻找开头等同于‘^’
print(re.findall(‘\Ahantao‘,‘hantao say hello 123_hantao‘))
#\Z寻找末尾,等同于‘$’
print(re.findall(‘hantao\Z‘,‘hantao say hello 123_hantao‘))
#重复匹配:. ? * + {}
#.:匹配任意字符,除了换行符
print(re.findall(‘a.c‘,‘a1c a%c abc acccc‘))
#.:加re.S或re.DOTALLD可匹配换行符
print(re.findall(‘a.c‘,‘a1c a%c abc acccc a\nc‘,re.S))
#?:左边那个字符出现0次或者1次
print(re.findall(‘ab?‘,‘ab ab a abbb‘))
#*:左边那个字符出现0次或者无穷次
print(re.findall(‘ab*‘,‘ab ab a abbb‘))
#+:左边那个字符出现1次或者无穷次
print(re.findall(‘ab+‘,‘ab ab a abbb‘))
#{n,m}:左边那个字符出现n,m次
print(re.findall(‘ab{3}‘,‘ab ab a abbb‘))
print(re.findall(‘ab{3,}‘,‘ab ab a abbb abbbbbb‘))
#.*  默认贪婪匹配 .*?非贪婪匹配
print(re.findall(‘a.*c‘,‘a1c a%c abc acccc‘))
print(re.findall(‘a.*?c‘,‘a1c a%c abc acccc‘))
#()分组
print(re.findall(‘<imag href="(.*)"/‘,‘<h1>hello</h1><a href="http://www.baidu.com"></a><imag href="http://www.baidu.com/a.jpg"/>‘))
#(?:)分组并全部保留,
print(re.findall(‘<imag href="(?:.*)"/‘,‘<h1>hello</h1><a href="http://www.baidu.com"></a><imag href="http://www.baidu.com/a.jpg"/>‘))
#|或者
print(re.findall(‘compan(?:y|ies)‘,‘too many companies have gone bankrupt,and next one is my company‘))
#match从头匹配
print(re.search(‘hantao‘,‘hantao say hello hantao‘).group())
print(re.match(‘hantao‘,‘hantao say hello hantao‘).group())
print(re.split(‘:‘,‘root:x:0:0:/root::/bin/bash‘))

 

二.logging模块

  1.日志级别

CRITICAL = 50 #FATAL = CRITICAL
ERROR = 40
WARNING = 30 #WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0 #不设置
"""
logging配置
"""

import os
import logging.config

# 定义三种日志输出格式 开始

standard_format = ‘[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]‘                   ‘[%(levelname)s][%(message)s]‘ #其中name为getlogger指定的名字

simple_format = ‘[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s‘

id_simple_format = ‘[%(levelname)s][%(asctime)s] %(message)s‘

# 定义日志输出格式 结束

logfile_dir = os.path.dirname(os.path.abspath(__file__))  # log文件的目录

logfile_name = ‘all2.log‘  # log文件名

# 如果不存在定义的日志目录就创建一个
if not os.path.isdir(logfile_dir):
    os.mkdir(logfile_dir)

# log文件的全路径
logfile_path = os.path.join(logfile_dir, logfile_name)

# log配置字典
LOGGING_DIC = {
    ‘version‘: 1,
    ‘disable_existing_loggers‘: False,
    ‘formatters‘: {
        ‘standard‘: {
            ‘format‘: standard_format
        },
        ‘simple‘: {
            ‘format‘: simple_format
        },
    },
    ‘filters‘: {},
    ‘handlers‘: {
        #打印到终端的日志
        ‘console‘: {
            ‘level‘: ‘DEBUG‘,
            ‘class‘: ‘logging.StreamHandler‘,  # 打印到屏幕
            ‘formatter‘: ‘simple‘
        },
        #打印到文件的日志,收集info及以上的日志
        ‘default‘: {
            ‘level‘: ‘DEBUG‘,
            ‘class‘: ‘logging.handlers.RotatingFileHandler‘,  # 保存到文件
            ‘formatter‘: ‘standard‘,
            ‘filename‘: logfile_path,  # 日志文件
            ‘maxBytes‘: 1024*1024*5,  # 日志大小 5M
            ‘backupCount‘: 5,
            ‘encoding‘: ‘utf-8‘,  # 日志文件的编码,再也不用担心中文log乱码了
        },
    },
    ‘loggers‘: {
        #logging.getLogger(__name__)拿到的logger配置
        ‘‘: {
            ‘handlers‘: [‘default‘, ‘console‘],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
            ‘level‘: ‘DEBUG‘,
            ‘propagate‘: True,  # 向上(更高level的logger)传递
        },
    },
}


def load_my_logging_cfg():
    logging.config.dictConfig(LOGGING_DIC)  # 导入上面定义的logging配置
    logger = logging.getLogger(__name__)  # 生成一个log实例
    logger.info(‘It works!‘)  # 记录该文件的运行状态

if __name__ == ‘__main__‘:
    load_my_logging_cfg()

 

三.time与datetime模块

在Python中,通常有这几种方式来表示时间:

  • 时间戳(timestamp):通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。
  • 格式化的时间字符串(Format String)
  • 结构化的时间(struct_time):struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一年中第几周,一年中第几天,夏令时)
import time
#--------------------------我们先以当前时间为准,让大家快速认识三种形式的时间
print(time.time()) # 时间戳:1487130156.419527
print(time.strftime("%Y-%m-%d %X")) #格式化的时间字符串:‘2017-02-15 11:40:53‘
print(time.localtime()) #本地时区的struct_time
print(time.gmtime())    #UTC时区的struct_time
#--------------------------按图1转换时间
# localtime([secs])
# 将一个时间戳转换为当前时区的struct_time。secs参数未提供,则以当前时间为准。
time.localtime()
time.localtime(1473525444.037215)
# gmtime([secs]) 和localtime()方法类似,gmtime()方法是将一个时间戳转换为UTC时区(0时区)的struct_time。
# mktime(t) : 将一个struct_time转化为时间戳。
print(time.mktime(time.localtime()))#1473525749.0
# strftime(format[, t]) : 把一个代表时间的元组或者struct_time(如由time.localtime()和
# time.gmtime()返回)转化为格式化的时间字符串。如果t未指定,将传入time.localtime()。如果元组中任何一个
# 元素越界,ValueError的错误将会被抛出。
print(time.strftime("%Y-%m-%d %X", time.localtime()))#2016-09-11 00:49:56
# time.strptime(string[, format])
# 把一个格式化时间字符串转化为struct_time。实际上它和strftime()是逆操作。
print(time.strptime(‘2011-05-05 16:37:06‘, ‘%Y-%m-%d %X‘))
#time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=16, tm_min=37, tm_sec=6,
#  tm_wday=3, tm_yday=125, tm_isdst=-1)
#在这个函数中,format默认为:"%a %b %d %H:%M:%S %Y"。
#--------------------------按图2转换时间
# asctime([t]) : 把一个表示时间的元组或者struct_time表示为这种形式:‘Sun Jun 20 23:21:05 1993‘。
# 如果没有参数,将会将time.localtime()作为参数传入。
print(time.asctime())#Sun Sep 11 00:43:43 2016
# ctime([secs]) : 把一个时间戳(按秒计算的浮点数)转化为time.asctime()的形式。如果参数未给或者为
# None的时候,将会默认time.time()为参数。它的作用相当于time.asctime(time.localtime(secs))。
print(time.ctime())  # Sun Sep 11 00:46:38 2016
print(time.ctime(time.time()))  # Sun Sep 11 00:46:38 2016

 

 

 

常用模块

原文:http://www.cnblogs.com/hantaozi430/p/7732782.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!