常用模块

Posted nyqxiaoqiang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了常用模块相关的知识,希望对你有一定的参考价值。


#random模块
# import random
# netword=‘‘
# for i in range(4):
# data = (random.randrange(0, 4))
# if data != i:
# tmp = chr(random.randint(65,95))
#
# else:
# tmp = random.randrange(0,9)
# netword +=str(tmp)
# print(netword)

#time模块
# import time
#
# # print(time.time())
# # print(time.localtime(123456789))
# # print(time.strptime("%y-%m-%d %H:%M:%S"%time.gmtime(12355622)))
# 将时间格式化
# print(time.gmtime(time.time()))
# print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))

#os模块
# import os
#import 获取当前目录
# print(os.getcwd())
# #返回上级目录
# print(os.chdir(r"E:PycharmProjectss14"))
# print(os.getcwd())
# #递归创建-删除
# # os.makedirs(r‘E:PycharmProjectss14ac‘)
# # os.removedirs(r‘E:PycharmProjectss14ac‘)
#
# # print(os.sep)
# # print(os.linesep)
# # print(os.listdir())
# # print(os.pathsep)
# print(os.system("ipconfig all"))
# print(os.stat(r‘E:PycharmProjects‘))
# print(os.environ)
#sys模块
# import sys
#
# print(sys.path)
# print(sys.argv)
#shutil 复制模块
import shutil
# f1=open("123",encoding="utf-8")
# f2=open("234","w",encoding="utf-8")
# shutil.copyfileobj(f1,f2)
# shutil.copyfile("123","456")
# shutil.make_archive("fuzhimokuai","zip","E:PycharmProjectss14day5")

# import zipfile
# z=zipfile.ZipFile("atm.zip","w")
# z.write("radom模块.py")
# z.close()

#持久化列表 shelve
# import shelve
# import datetime
# d = shelve.open(‘p_text‘) # 打开一个文件
# # print(d.get("name"))
# # print(d.get("info"))
# # print(d.get("date"))
# #
# info = {‘age‘:22,"job":‘it‘}
# name = ["alex", "rain", "test"]
# d["name"] = name # 持久化列表
# d["info"] = info # 持久dict
# d[‘date‘] = datetime.datetime.now()
# d.close()

#xml处理

# import xml.etree.ElementTree as ET
# tree=ET.parse("xmltest.xml")
# root=tree.getroot()
# print(root.tag)
#
# # for c in root:
# # print(c.tag,c.attrib)
# # for i in c:
# # print(i.tag,i.text,i.attrib)
#
# for i in root.iter("year"):
# print(i.text)

#xml修改
# import xml.etree.ElementTree as ET
# terr=ET.parse("xmltest.xml")
# root=terr.getroot()
# # 修改
# for nide in root.iter(‘year‘):
# new_year=int(nide.text)+1
# nide.text=str(new_year)
# nide.set("downup","no")
# terr.write("xmltest.xml")

#删除
# for country in root.findall("country"):
# rank =int(country.find("rank").text)
# if rank < 50:
# root.remove(country)
# terr.write(‘output.xml‘)
#创建
# import xml.etree.ElementTree as ET
#
# new_xml=ET.Element("datalist")
# data=ET.SubElement(new_xml,"data",attrib={"undatd":"by"})
# name=ET.SubElement(data,"name",attrib={"undatd":"by"})
# name.text=‘xiaoqiang‘
#
# et=ET.ElementTree(new_xml)
# et.write("text3.xml",encoding="utf-8",xml_declaration=True)
# ET.dump(new_xml)

#文件配置模块 configparser

# import configparser

# config=configparser.ConfigParser()
# config["DEFAULT"]={
# "setting":"sql",
# "data":"file",
# "name":"qiang"
# }
# config["tag"]={}
# config["tag"]["python"]=‘yes‘
#
# config["attrib"]={}
# config["attrib"]["atime"]=‘0913‘
# config["attrib"]["ctime"]="0912"
#
# config["DEFAULT"]["age"]=‘22‘
#
# with open("config.inx","w") as f:
# config.write(f)
#读
# config.read("config.inx")
#
# print(config.defaults())
# print(config["attrib"]["ctime"])

#加密模块 hashlib

# import hashlib
#
# a = hashlib.sha1()
# a.update(b"hello")
# print(a.hexdigest())
#
# a.update("你好".encode(encoding="utf8"))
# print(a.hexdigest())

# 正则表达式

# import re
# core=re.match(‘aa?‘,"aahello123bcd")
# print(core)
# core=re.search(‘[0-9](2)‘,"aahellsejio123dd")
# print(core)
import re
parser_str = ‘1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )‘

#完成
import re
def chengchu(s): # 处理带负号的乘除,负号歪打正着处理成功了
r = re.compile(‘[d.?d]+[*/]-?[d.]+‘)
while re.search(‘[*/]‘, s):
ma = re.search(r, s).group()
# print(ma)
li = re.findall(r‘(-?[d.]+|*|/)‘, ma)
if li[1] == ‘*‘:
result = str(float(li[0]) * float(li[2]))
else:
result = str(float(li[0]) / float(li[2]))
s = s.replace(ma, result)
return s


def jiajian(s): # 处理加减法,变成数组,全加
li = re.findall(r‘([d.]+|+|-)‘, s)
sum = 0
for i in range(len(li) - 1): # 处理有两个--号连续的情况
if li[i] == ‘-‘ and li[i + 1] == ‘-‘:
li[i] = ‘+‘
li[i + 1] = ‘+‘
for i in range(len(li)):
if li[i] == ‘-‘:
li[i] = ‘+‘
li[i + 1] = float(li[i + 1]) * -1
for i in li:
if i == ‘+‘:
i = 0
sum = sum + float(i)
return str(sum)


def simple(s): # 处理不带括号的
return jiajian(chengchu(s))


def complex(s): # 处理带括号的
while ‘(‘ in s:
reg = re.compile(r‘([^()]+)‘)
ma = re.search(reg, s).group()
result = simple(ma[1:-1])
s = s.replace(ma, result, 1)
return simple(s)


ss = ‘1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )‘.replace(‘ ‘, ‘‘)
print(complex(ss))
print(eval(ss))
#
#日志模块logging
import logging

# logging.basicConfig(filename="log.log",
# format="%(asctime)s-%(name)s-%(module)s -%(levelname)s-%(message)s",
# datefmt="%H",
# level=logging.INFO)
# logging.debug(‘This message should go to the log file‘)
# logging.info(‘So should this‘)
# logging.warning(‘And this, too‘)

# import logging
# #
# # create logger
# logger=logging.getLogger("gaotie")
# logger.setLevel(logging.DEBUG)
# # 创建控制台处理程序并设置调试级别
# ch=logging.StreamHandler()
# ch.setLevel(logging.DEBUG)
#
# # 创建文件处理程序并将其设置为警告
# fh=logging.FileHandler("GAOTIE.log")
# fh.setLevel(logging.DEBUG)
# # create formatter
# formatter=logging.Formatter("%(asctime)s-%(name)s-%(levelname)s:%(message)s")
#
# # 将格式化程序添加到CH和FH
# ch.setFormatter(formatter)
# fh.setFormatter(formatter)
#
# # 将CH和FH添加到记录器
# logger.addHandler(ch)
# logger.addHandler(fh)
#
# # 应用程序代码
# logger.debug(‘debug message‘)
# logger.info(‘info message‘)
# logger.warn(‘warn message‘)
# logger.error(‘error message‘)
# logger.critical(‘critical message‘)

































































































































































































































































以上是关于常用模块的主要内容,如果未能解决你的问题,请参考以下文章

Python 常用模块学习

如何使用模块化代码片段中的LeakCanary检测内存泄漏?

C#常用代码片段备忘

swift常用代码片段

# Java 常用代码片段

# Java 常用代码片段