python开发基础(四)模块

  1 # 模块
  2 
  3 """
  4 python标准库  直接 import 导入
  5 第三方模块  pip 下载 , import 导入
  6 程序自定义的模块库
  7 """
  8 
  9 # 系统模块
 10 import time  # 时间
 11 import datetime  # 日期时间
 12 import random  # 随机模块
 13 import os  # 操作系统交互
 14 import sys  # 解释器交互
 15 import json  # json 信息
 16 import pickle  # 序列化, 反序列化
 17 import shelve  # 序列化模块, 比 pickle简单, 只有open一个函数, 返回字典, 可读写, key为字符串, value为python支持的所有类型
 18 import xml.etree.ElementTree as ET  # xml 模块
 19 import re  # 正则表达式, 字符串的匹配
 20 import logging  # 日志文件
 21 import configparser  # 配置文件模块
 22 import hashlib  # hash算法, MD5
 23 
 24 print('基础模块:time, datetime, random, os, sys, json, pickle, shelve, xml, re, logging, configparser, hashlib')
 25 
 26 
 27 def time_module():
 28     print(time.time())  # 时间戳(秒数) float 格式, 从1970-1-1-00.00.00开始算起, 到现在的走过的秒 1622619938
 29     print(time.localtime())  # 结构化时间, 时间对象, 当前时区时间
 30     print(time.gmtime())  # 时区为0的结构化时间 世界标准时间UTC
 31     # 时间戳-->>结构化时间
 32     print(time.localtime(time.time()))
 33     # 结构化时间-->>时间戳
 34     print(time.mktime(time.localtime()))
 35     # 结构化时间-->>字符串时间
 36     print(time.strftime('%Y-%m-%d %X', time.localtime()))  # '%Y(年)-%m(月)-%d(日) %X(时分秒)' , localtime 为结构化时间
 37     # 字符串时间-->>结构化时间
 38     print(time.strptime('2021:06:02:15:57:49', '%Y:%m:%d:%X'))
 39     # 结构化时间-->>固定形式 '周 月 日 时 分 秒 年'
 40     print(time.asctime())  # 默认为time.localtime
 41     # 时间戳-->>固定形式 '周 月 日 时 分 秒 年'
 42     print(time.ctime())  # 默认为time.time
 43 
 44     massage = '\n↑↑↑以上为time模块\n'
 45     return massage
 46 
 47 
 48 def data_time_module():
 49     print(datetime.datetime.now())  # 显示当前时间 '年-月-日 时:分:秒'
 50 
 51     massage = '\n↑↑↑以上为data time模块\n'
 52     return massage
 53 
 54 
 55 def random_module():
 56     list_num = []
 57     for i in range(11):
 58         list_num.append(i)
 59     set_num = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
 60     print(random.random())  # 默认随机生成 (0-1) 的 float
 61     print(random.randint(1, 3))  # 随机生成 (1, 3) 的 int
 62     print(random.randrange(1, 3))  # 随机生成 (1, 3] 的 int
 63     print(random.choice(set_num))  # 随机生成 list, set等 里的一个元素
 64     print(random.sample(list_num, 3))  # 随机生成 list, set等 中的多个元素, 以 list 的方式输出
 65     print(random.uniform(1.5, 1.6))  # 随机生成 (1.5, 1.6) 中的一个 float
 66     # 随机排列列表 ***只限于列表***
 67     print('原列表', list_num)
 68     random.shuffle(list_num)
 69     print('执行random.shuffle后的列表', list_num)
 70 
 71     massage = '\n↑↑↑以上为random模块\n'
 72     return massage
 73 
 74 
 75 def os_module():
 76     print(os.getcwd())  # 当前工作路径
 77     # print(os.environ)  # 查看系统环境变量
 78     # os.chdir('pythonBasicPackageUse')  # 更改当前路径下的其他文件夹为当前工作路径
 79     # os.makedirs('test1/test2')  # 在工作目录下新建文件夹, 可以递归
 80     # os.removedirs('test1/test2')  # 在工作目录下删除文件夹, 可以递归, 如果上层不为空则无法删除
 81     # os.mkdir()  # 新建一个文件夹
 82     # os.rmdir()  # 删除一个文件夹
 83     # os.remove()  # 删除一个文件
 84     # os.rename()  # 重命名一个文件
 85     # print(os.listdir())  # 获取当前工作目录的所有文件, 以列表方式输出
 86     # print(os.stat('1.py'))  # 查看文件的信息
 87     # print(os.path.dirname(os.getcwd()))  # 返回上级目录
 88     # print(os.path.split(r'E:\my_project\VScodeNote\python'
 89     #                     r'\python_Code\pythonBasicPackageUse\code_module\os1.py'))  # 返回文件夹和文件
 90     # print(os.path.dirname(r'E:\my_project\VScodeNote\python'
 91     #                       r'\python_Code\pythonBasicPackageUse\code_module\os1.py'))  # 返回上一级目录
 92     # print(os.path.basename(r'E:\my_project\VScodeNote\python'
 93     #                        r'\python_Code\pythonBasicPackageUse\code_module\os1.py'))  # 输出当前文件名字
 94     dirname1 = 'E:\my_project\VScodeNote\python'
 95     dirname2 = 'python_Code\pythonBasicPackageUse\code_os_module\os1.py'
 96     # print(os.path.join(dirname1, dirname2))  # 路径拼接
 97 
 98     massage = '\n↑↑↑以上为os模块\n'
 99     return massage
100 
101 
102 def sys_module():
103     print(sys.argv)  # 工作路径, 含文件名
104     for i in range(100):
105         sys.stdout.write('#')
106         time.sleep(0.2)
107         sys.stdout.flush()
108     print()
109     # print(sys.version)  # python解释器的版本
110     # print(sys.path)
111 
112     massage = '\n↑↑↑以上为sys模块\n'
113     return massage
114 
115 
116 def json_module():
117     dic = {'name': 'jack'}
118     msg_json = json.dumps(dic)  # 转为str
119     print(msg_json)
120     print(type(msg_json))
121     os.chdir('file')
122 
123     # 写json
124     # f_w = open('new_file', 'w')
125     # f_w.write(msg_json)
126     # f_w.close()
127 
128     # 从文件中读json
129     f_r = open('new_file', 'r')
130     f_data = json.loads(f_r.read())  # 使用loads时必须符合json语法
131     print(f_data)
132     print(type(f_data))
133     # print(f_data['name'])
134 
135     f_r.close()
136     os.chdir('..')
137 
138     massage = '\n↑↑↑以上为json模块\n'
139     return massage  # #
140 
141 
142 def pickle_module():  # 数据序列化类型更多
143     dic = {'name': 'jack', 'age': '18', 'sex': 'male'}
144     print(type(dic))
145     pick_data = pickle.dumps(dic)  # 转为bytes
146     # print(pick_data, type(pick_data))
147 
148     os.chdir('file')
149 
150     # 写pickle
151     # f_w = open('pickle_file', 'wb')
152     # f_w.write(pick_data)
153     # f_w.close()
154 
155     # 读pickle
156     f_r = open('pickle_file', 'rb')
157     f_data = pickle.loads(f_r.read())
158     print(f_data['name'], type(f_data))
159 
160     f_r.close()
161     os.chdir('..')
162 
163     massage = '\n↑↑↑以上为pickle模块\n'
164     return massage
165 
166 
167 def shelve_module():
168     os.chdir('file')
169     f_w = shelve.open(r'shelve_file')
170     # f_w['stu1_info'] = {'name': 'jack', 'age': '18', 'sex': 'male'}
171     # f_w['stu2_info'] = {'name': 'jack_f', 'age': '20'}
172     # f_w['school_info'] = {'home': 'amfc.ltd', 'city': 'China'}
173     #
174     print(f_w.get('stu1_info')['name'])
175     f_w.close()
176     os.chdir('..')
177 
178     massage = '\n↑↑↑以上为shelve模块\n'
179     return massage
180 
181 
182 def xml_module():
183     os.chdir('file')
184     tree_file = ET.parse('xml_file')
185     root_file = tree_file.getroot()
186     # print(root_file.tag)
187 
188     # 遍历xml文件
189     """
190     for i in root_file:
191         tag_1 = i.tag  # tag: 标签, 节点  eg: <tag>text</tag>
192         attrib_1 = i.attrib  # attrib: 标签属性  eg: <tag attrib[key] = 'attrib[value]'>text</tag>
193         text_1 = i.text  # text: 标签中包含的数据  eg: <tag>text</tag>
194 
195         print(tag_1)  # 只会输出节点的名字
196         print(attrib_1)  # 输入每个tag的属性
197         # print(text_1)
198 
199         print('-' * 50)
200 
201         for j in i:  # 第二个循环
202             tag_2 = j.tag  # 子标签  eg: <tag>text</tag>
203             attrib_2 = j.attrib  # 子标签属性  eg: <tag attrib[key] = 'attrib[value]'>text</tag>
204             text_2 = j.text  # 字标签中包含的数据  eg: <tag>text</tag>
205 
206             print(tag_2)
207             print(attrib_2)
208             print(text_2)
209 
210             print('-' * 20)
211         print('-' * 50)
212 
213     for singer in root_file.iter('year'):  # 取单一标签中的信息
214         print(singer.tag, singer.text)
215         """
216 
217     # 修改xml文件
218     """
219     for tag_file in root_file.iter('year'):
220         # 修改标签中的信息
221         new_year = int(tag_file.text) + 1
222         tag_file.text = str(new_year)
223         # 修改标签属性
224         tag_file.set('updated', 'yes')  # key和value用 ', ' 分割
225     tree_file.write('xml_file')  # 文件名字不变 == 覆盖文件
226     """
227 
228     # 删除xml文件内容
229     """
230     for tag_file in root_file.findall('country'):  # findall 找多个标签
231         rank = int(tag_file.find('rank').text)  # find找一个标签
232         if rank >= 50:
233             root_file.remove(tag_file)
234     tree_file.write('new_xml_file')
235     """
236 
237     # 创建xml文件
238     """
239     # Element: 创建一个根节点为 'member' 标签
240     new_xml = ET.Element('member')
241     # SubElement: 创建子标签(哪个父标签创建, 子标签名, attrib(属性) = {'key(标签属性)': 'value(值)'})
242     name_tag1 = ET.SubElement(new_xml, 'name', attrib={'enrolled': 'yes'})
243     age_tag1 = ET.SubElement(name_tag1, 'age', attrib={'checked': 'no'})
244     sex_tag1 = ET.SubElement(name_tag1, 'sex')
245     # sex标签中的数据
246     age_tag1.text = 'male'
247     sex_tag1.text = '20'
248 
249     name_tag2 = ET.SubElement(new_xml, 'name', attrib={'enrolled': 'yes'})
250     age_tag2 = ET.SubElement(name_tag2, 'age', attrib={'checked': 'no'})
251     sex_tag2 = ET.SubElement(name_tag2, 'sex')
252     age_tag2.text = 'male'
253     sex_tag2.text = '22'
254 
255     name_tag3 = ET.SubElement(new_xml, 'name', attrib={'enrolled': 'yes'})
256     age_tag3 = ET.SubElement(name_tag3, 'age', attrib={'checked': 'no'})
257     sex_tag3 = ET.SubElement(name_tag3, 'sex')
258     age_tag3.text = 'female'
259     sex_tag3.text = '30'
260 
261     xml_file = ET.ElementTree(new_xml)  # 生成文档对象
262     xml_file.write('own_xml', encoding='utf8', xml_declaration=True)  # 写入文档
263 
264     ET.dump(new_xml)
265     """
266 
267     os.chdir('..')
268 
269     massage = '\n↑↑↑以上为xml模块\n'
270     return massage
271 
272 
273 def re_module():
274     file = " . ^ $ * + ? {} [] | () \ "  # 元字符
275     """
276     .  通配符 每个 '.' 代表1个字符, 除了 "\n"
277     ^  表示开头, 必须放在开头
278     $  表示结尾,放在结尾
279     *  表示重复
280     +  表示重复, 最后一个字符重复
281     ?  同样的字符多取一个 字符个数区间-->?(0, 1)
282     {}  {0, } == *
283         {1, } == +
284         {0, 1} == ?
285     []  字符集, 功能符号: - eg:[0-9], [a-z]
286                         ^ 表示非
287                         / 转为普通字符
288     |  表示或
289     ()  表示分组
290     \  转义符
291         \d == 匹配任何10进制的数[0, 9]
292         \D == 匹配任何非10进制的数
293         \s == 匹配任何空白字符
294         \S == 匹配任何非空白字符
295         \w == 匹配任何字母数字[0-9a-zA-Z]
296         \W == 匹配任何非字母数字[^0-9a-zA-Z]
297         \b == 匹配一个特殊符号边界, eg: & # 等
298     """
299 
300     # findall  # 满足匹配条件 存在列表里
301     # print(re.findall('..ja..ck', 'asjaasckkkkdafgrthdasdajaasckkkqwefaszxvaajaqeckkkk'))
302     # print(re.findall('jac[abcdefghijklmnopqrstuvwxyz]', 'jack'))
303     # print(re.findall('jac[^a-z]*', 'jac1kq123'))
304     # print(re.findall('jack|l', 'jack1jacljack1lljack'))
305     # print(re.findall(r'I\b', 'I am jack'))
306 
307     # search  匹配成功返回对象, 匹配失败,返回空, 只会匹配第一个; 通过group()方法得到匹配成功后的字符串, 函数本身返回为对象(object)类型
308 
309     test_b = re.search('a((bc)|(ac))d', 'abcd')
310     print(test_b.group())
311     # print(type(test_b.group()))
312 
313     module_search = re.search('(?P<name>[a-z]+)(?P<age>\d+)', 'jack18alex36xiaoming33')
314     print(module_search.group('name', 'age'))
315 
316     # split  分隔
317     module_split1 = re.split('[ |]', 'hello world|!')
318     print(module_split1)
319     module_split2 = re.split('[ab]', 'abcab')
320     print(module_split2)
321 
322     # sub 替换
323     module_sub = re.sub('\d', 'A', 'asdasd654asd654asd541sad3asd4asd4q')
324     print(module_sub)
325 
326     # subn 替换 返回元组, (返回内容, 返回匹配次数)
327     module_subn = re.subn('\d', 'A', 'asdasd654asd654asd541sad3asd4asd4q')
328     print(module_subn)
329 
330     # compile  编译封装正则表达式的方法
331     module_compile = re.compile('\d')
332     compile_file = module_compile.findall('asd74asd447664as465d654qw654asd321')
333     print(compile_file)
334 
335     # finditer 封装到迭代器
336     finditer_module = re.finditer('\d', 'asd546as546d513as1d53as1d54a6sd')
337     ll = []
338     for i in finditer_module:
339         i = i.group()
340         ll.append(i)
341     print(ll)
342 
343     massage = '\n↑↑↑以上为re模块\n'
344     return massage
345 
346 
347 def logging_module():
348     # logging.basicConfig(
349     #     level=logging.DEBUG,
350     #     filename='../python_Code/file/logger.log',
351     #     filemode='w',
352     #     format='%(asctime)s %(filename)s [%(lineno)d] :%(message)s'
353     # )
354 
355     logger1 = logging.getLogger('my_logging')
356     logger1.setLevel(logging.DEBUG)  # 日志输出优先级
357     fh1 = logging.FileHandler('../python_Code/file/log.log')  # 日志输入文件地址
358     ch1 = logging.StreamHandler()  # 输出到控制台
359 
360     fm = logging.Formatter('%(asctime)s %(filename)s [%(lineno)d] :%(message)s')  # 输入格式
361 
362     # 格式化日志输出格式
363     fh1.setFormatter(fm)
364     ch1.setFormatter(fm)
365 
366     logger1.addHandler(fh1)
367     logger1.addHandler(ch1)
368 
369     logger2 = logging.getLogger('my_log.log')
370     logger2.setLevel(logging.INFO)
371     fh2 = logging.FileHandler('../python_Code/file/log_new.log')
372     ch2 = logging.StreamHandler()
373 
374     fh2.setFormatter(fm)
375     ch2.setFormatter(fm)
376 
377     logger2.addHandler(fh2)
378     logger2.addHandler(ch2)
379 
380     logger1.debug('1 debug message')
381     logger1.info('1 info message')
382     logger1.warning('1 warning message')
383     logger1.error('1 error message')
384     logger1.critical('1 critical message')
385 
386     logger2.debug('2 debug message')
387     logger2.info('2 info message')
388     logger2.warning('2 warning message')
389     logger2.error('2 error message')
390     logger2.critical('2 critical message')
391 
392     # logging.debug('debug message')
393     # logging.info('info message')
394     # logging.warning('warning message')
395     # logging.error('error message')
396     # logging.critical('critical message')
397 
398     print()
399 
400     message = '\n↑↑↑以上为logging模块\n'
401     return message
402 
403 
404 def configparser_module():
405     # 生成一个配置文件
406     config = configparser.ConfigParser()  # config = {}
407     config['DEFAULT'] = {'ServerAliveInterval': '45',
408                          'Compression': 'yes',
409                          'CompressionLevel': '9',
410                          'ForWardX11': 'yes'}
411 
412     config['bitbucket.org'] = {}
413     config['bitbucket.org']['User'] = 'hg'
414 
415     config['topsecret.server.com'] = {}
416     top = config['topsecret.server.com']
417     top['Host Port'] = '50022'
418     top['ForwardX11'] = 'no'
419 
420     with open('../python_Code/file/configfile_new', 'w') as configfile:
421         config.write(configfile)
422 
423     # 读配置文件
424     config.read('../python_Code/file/configfile')
425     print(config.sections())  # 读取文件的所有键
426 
427     # 判断
428     # print('server.com' in config)
429 
430     # 查询
431     # print(config['bitbucket.org']['User'])
432 
433     # 循环遍历
434     for key in config['topsecret.server.com']:
435         # print(key)
436         pass
437 
438     # 取键, 返回列表
439     # print(config.options('bitbucket.org'))  # 默认把[DEFAULT]一起取出
440 
441     # 取键值对, 键值对返回元组, 列表嵌套
442     # print(config.items('bitbucket.org'))
443 
444     # 取值
445     # print(config.get('bitbucket.org', 'compression'))
446 
447     # 删,改(覆盖),增
448     # 增(块)
449     config.add_section('Other')
450     config.add_section('Other1')
451     # 增(配置)
452     config.set('Other', 'other1', '1')  # 用逗号分隔
453     config.set('Other', 'other2', '2')
454     # 删(块)
455     config.remove_section('Other1')
456     # 删(配置)
457     config.remove_option('Other', 'Other1')
458 
459     config.write(open('../python_Code/file/configfile_new', 'w'))
460 
461     configfile.close()
462 
463     print()
464     message = '\n↑↑↑以上为configparser模块\n'
465     return message
466 
467 
468 def hashlib_module():
469     obj1 = hashlib.md5()
470     obj2 = hashlib.sha256()
471     obj1.update('Amfc0-./'.encode('utf8'))
472 
473     print(obj1.hexdigest())
474 
475     print()
476     message = '\n↑↑↑以上为hashlib模块\n'
477     return message
478 
479 
480 # print(time_module())
481 # print(data_time_module())
482 # print(random_module())
483 # print(os_module())
484 # print(sys_module())
485 # print(json_module())
486 # print(pickle_module())
487 # print(shelve_module())
488 # print(xml_module())
489 # print(re_module())
490 # print(logging_module())
491 # print(configparser_module())
492 # print(hashlib_module())

 

posted @ 2021-06-21 18:59  Alice只敲代码不秃头  阅读(104)  评论(0编辑  收藏  举报