Python学习历程之模块浅识
# =============================操作系统模块=======================
# import os
# 待续
# ==============================解释器模块========================
# import sys
# 待续
# ===============================加密============================
# import hashlib
#
# m = hashlib.md5()
# m.update("HelloWorld".encode("utf8"))
# print(m.hexdigest())
#
# s = hashlib.sha256()
# s.update("HelloWorld".encode("utf8"))
# print(s.hexdigest()) # ======================日志=====================
import logging
# 日志配置
# logging.basicConfig(level=logging.DEBUG,
# format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
# datefmt='%a,%d %b %Y %H:%M:%S',
# filename='test.log',
# filemode='a')
#
# logging.debug("degub message")
# logging.info("info message")
# logging.warning("warning message")
# logging.error("error message")
# logging.critical("critical message") # 日志函数处理日志
# logging.basicConfig(level=logging.DEBUG)
# logger = logging.getLogger()
# #创建一个handler 用于写入日志文件
# fh = logging.FileHandler('test.log')
# #在创建一个handler,用于输出到控制台
# ch = logging.StreamHandler()
#
# formamtter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
#
# fh.setFormatter(formamtter)
# ch.setFormatter(formamtter)
#
# logger.addHandler(fh)
# logger.addHandler(ch)
#
# logger.debug("degub message")
# logger.info("info message")
# logger.warning("warning message")
# logger.error("error message")
# logger.critical("critical message") # ===========================生成和修改常见配置文档==================
# import configparser
#
# config = configparser.ConfigParser()
# 创建配置文件 example.ini ,写入数据
# config['DEFAULT']={'ServerAliveInterval':'45',
# 'Compression':'yes',
# 'CompressionLevel':'9'}
# config['bitbucket.org']={}
# config['bitbucket.org']['User']='hg'
#
# with open('example.ini','w') as configfile:
# config.write(configfile)
# 读取配置文件得数据
# config.read('example.ini')
# print(config.sections())
# print(config.defaults())
# 判断数据是否在配置文件中
# print('bitbucket.org' in config)
# print('bitbucke' in config)
# 单独取值
# print(config['bitbucket.org']['user'])
# 循环取值
# for key in config['bitbucket.org']:
# print(key) # 还默认打印Default里面得东西
# 复制粘贴
# config.remove_section('topsecret.server.com')#删除块
# config.remove_option('bitbucket.org','user') # 删除模块下的键值对
# config.write(open('example.ini','w'))
# 修改
# config.set('bitbucket.org','user','alex') # =======================匹配与正则表达式===========================
# string提供的方法是完全匹配
# s = 'hello world'
# print(s.find('llo'))
# ret = s.replace('ll','xx')
# print(ret)
# print(s.split(' '))
# print(s.split('w'))
# 正则表达式提供的方法是模糊匹配
# 字符匹配(普通字符,元字符):
# 普通字符:大多数的字符和字母都会和自身匹配
# 2元字符: . ^ $ * + ? { } [ ] | ( ) \
# import re
# ---------- . : 通配符 -------------
# res =re.findall('w\w{2}l','hello world') # 匹配的内容
# res = re.findall('alex','adfsfsdkljblldfsdf')
# res = re.findall('w..l','hello world') # . 代之所有的一个字符除了换行符
# res = re.findall('w.l','hello w \nld')
# --------- ^ : 尖角符 ----------------
# res = re.findall('^h...o','hjasdhello') # ^ 开头匹配
# --------- $ : dollar符 -----------------
# res = re.findall('a..x$','sdfsalex') # $ 结尾匹配
# --------- * :星符 ---------------
# res = re.findall('a.*li','fsdfsfasdfsfsdlisdfsdfse') # 重复匹配[0,+oo]
# --------- + : 加号符 --------------
# res = re.findall('b+','kajsfbhbbb') # 匹配[1,+oo]个前面的字符
# --------- ? :问好符 -------------
# res = re.findall('ab?','adfsfab') # 匹配[0,1]个前面的字符
# --------- { } :大括号符 ------------
# res = re.findall('a{5}b','aaaaabaaab') # 匹配指定次数的字符
# res = re.findall('a{1,3}b','abaabaaabaaaab') # 匹配指定范围数的字符
# --------- [ ] :中括号符(字符集) ------------
# res = re.findall('a[c,b]x','acx') # 字符集合 或者的关系,只能选一种
# res = re.findall('a[a-z]x','azx') # [a-z] :a,b,c,d...x,y,z
# res = re.findall('a[.*|]x','adbsa|xsda.xfa*xdfsf') # 取消元字符的特殊功能除了(\ ^ -)
# res = re.findall('[1-9,a-z,A-Z]','12tyAS') #全部匹配
# res = re.findall('[1-9a-zA-Z]','12tyAS') #全部匹配
# res = re.findall('[^t]','12tyAS') # ^ 在 []中求反
# res = re.findall('[^iu]','iusdfsfsdf') # ^ 在 [] 中非的意思
# --------- | : 管道符 ------------
# res = re.search('(as)|3','3asf3').group() # 管道符是或的意思
# --------- ( ) : 括号符 -----------
# res = re.search('(as)+','sdfsasas').group() # 括号是分组
# res = re.search('(?P<id>\d{3})/(?P<name>\w{3})','weew34ttt123/ooo')
# res = re.findall('www.(?:\w+).com','www.baidu.com') # ?: 取消组的优先级
# --------- \ : 斜杠符 -----------
# 反斜杠后边跟元字符去除特殊功能
# 反斜杠后面跟普通字符实现特殊功能
# \d 匹配任意十进制数 [0-9]
# \D 匹配任意非数字字符 [^0-9]
# \s 匹配任意空白字符 [\t\n\r\f\v]
# \S 匹配任意非空白字符 [^\t\n\r\f\v]
# \w 匹配任意字母数字符 [a-zA-Z0-9]
# \W 匹配任意非字母数字符 [^a-zA-Z0-9]
# \b 匹配一个特殊字符边界,也就是指单词和空格间的位置 # -----------------------------------------
# 结论: * 等价于{0,正无穷} + 等价于{1,正无穷} ? 等价于{0,1}
# ----------------------------------------- # -----------------正则表达式的方法-------------
# re.findall() #返回满足条件的所有结果到一个列表里
# re.fullmatch() #全模式匹配
# re.finditer() #返回匹配结果的迭代器
# re.search() # 匹配返回满足条件的第一个结果可以调用group()返回结果
# re.match() #只在字符串开始匹配
# re.split() # 分割
# re.sub() # 替换
# re.subn() # 替换
# obj = re.compile('.com') # 编译成正则对象
# print(res.group())
# print(res.group('id'))
# print(res.group('name'))
# print(res) # ========================模块============================
# 一个.py文件就为一个模块
# import calculate
# import sys
# print(sys.path)
# print(sys.platform)
# print(calculate.add(1,2,3,4,5)) # ======================JSON 或者 Pickle 或者 shelve=============================
# import json # dt = {'12':'asdf'}
# data = json.dumps(dt)
# with open('18.txt','w') as fd:
# fd.write(data) # with open('18.txt','r') as fd:
# data = fd.read()
# data = json.loads(data)
# print(data)
# print(type(data)) # import pickle
# def foo():
# print("ok")
# data = pickle.dumps(foo)
# with open('18.txt','wb') as fd:
# fd.write(data) # with open('18.txt','rb') as fd:
# data = fd.read()
# data = pickle.loads(data)
# print(type(data))
# print(data)
# data() # import shelve
# f = shelve.open('19.txt')
# f['info'] = {'name':'alex','age':'18'}
# print(f.get('info')['name']) # d = {'name':'alex','age':'18'}
# print(d.get('sex','male')) # class F1:
# def __init__(self):
# self.name = 123
# print('F1',self.name)
# class F2:
# def __init__(self,a):
# self.ff = a
# print('F2',self.ff.name)
#
# class F3:
# def __init__(self,b):
# self.dd = b
# print('F3',self.dd.ff.name)
# f = F1()
# f2 = F2(f)
# f3 = F3(f2) # =========================执行命令其他进程并返回值====================================
# import subprocess
#
# obj = subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE) #将子进程转移到主进程
# print(obj)
# print(obj.stdout)
# print(str(obj.stdout.read(),'gbk')) # ==========================字符编码=================================
# str : unicode
# bytes : 16进制 # ===========================线程进程模块=============================
# ---------------- 普通锁 --------------------
# import time
# import threading
# begin = time.time()
# def foo():
# print('foo')
# time.sleep(1)
# def bar():
# print('bar')
# time.sleep(2)
# t1 = threading.Thread(target=foo)
# t2 = threading.Thread(target=bar)
# t1.start()
# t2.start()
# end = time.time()
# print(end-begin) # from time import sleep,ctime
# import threading
#
# num = 1000
# def foo():
# global num
# r.acquire()
# num -= 1
# sleep(0.1)
# r.release()
#
#
# def main():
# begin = ctime()
# print(begin)
# threadList = []
# for i in range(100):
# t=threading.Thread(target=foo())
# threadList.append(t)
# for i in threadList:
# i.start()
# # for i in threadList:
# # i.join()
# end = ctime()
# print(num)
# print(end)
#
# if __name__ == '__main__':
# r = threading.Lock()
# main() # ------------------递归锁-------------------------------- # import threading
# import time
# class MyThread:
# def doA(self):
# rlock.acquire()
# print('A gets rlock')
# time.sleep(3)
# rlock.acquire()
# print('A gets rlock')
# time.sleep(1)
# rlock.release()
# rlock.release()
# def doB(self):
# rlock.acquire()
# print('B gets rlock')
# time.sleep(2)
# rlock.acquire()
# print('B gets rlock')
# time.sleep(2)
# rlock.release()
# rlock.release()
# def do(self):
# self.doA()
# self.doB()
#
# if __name__ == '__main__':
# # lockA = threading.Lock()
# # lockB = threading.Lock()
# rlock = threading.RLock()
# lockList = []
# for i in range(5):
# t = threading.Thread(target=MyThread().do())
# lockList.append(t)
# for i in lockList:
# i.start()
# for i in lockList:
# i.join()
# print('======end====') # -------------------信号量---------------------------- # import threading
# import time
#
# class MyThread(threading.Thread):
# def run(self):
# if semaphore.acquire():
# print(self.name)
# time.sleep(2)
# semaphore.release()
#
# if __name__ == '__main__':
# semaphore = threading.BoundedSemaphore(5)
# thrs = []
# for i in range(23):
# thrs.append(MyThread())
# for i in thrs:
# i.start() # -------------------------------条件变量------------------------------------ # import threading,time
# from random import randint
#
# class Producer(threading.Thread):
# def run(self):
# global L
# while True:
# val=randint(0,100)
# print('生产者',self.name,":Append"+str(val),L)
# if lock_con.acquire():
# L.append(val)
# lock_con.notify()
# lock_con.release()
# time.sleep(3)
# class Consumer(threading.Thread):
# def run(self):
# global L
# while True:
# lock_con.acquire()
# if len(L)==0:
# lock_con.wait()
# print('消费者',self.name,":Delete"+str(L[0]),L)
# del L[0]
# lock_con.release()
# time.sleep(0.25)
#
# if __name__=="__main__":
#
# L=[]
# lock_con=threading.Condition()
# threads=[]
# for i in range(5):
# threads.append(Producer())
# threads.append(Consumer())
# for t in threads:
# t.start()
# for t in threads:
# t.join()
Python学习历程之模块浅识的更多相关文章
- Python学习 Part4:模块
Python学习 Part4:模块 1. 模块是将定义保存在一个文件中的方法,然后在脚本中或解释器的交互实例中使用.模块中的定义可以被导入到其他模块或者main模块. 模块就是一个包含Python定义 ...
- python学习之argparse模块
python学习之argparse模块 一.简介: argparse是python用于解析命令行参数和选项的标准模块,用于代替已经过时的optparse模块.argparse模块的作用是用于解析命令行 ...
- Python学习day19-常用模块之re模块
figure:last-child { margin-bottom: 0.5rem; } #write ol, #write ul { position: relative; } img { max- ...
- Python学习day18-常用模块之NumPy
figure:last-child { margin-bottom: 0.5rem; } #write ol, #write ul { position: relative; } img { max- ...
- python学习之random模块
Python中的random模块用于生成随机数.下面介绍一下random模块中最常用的几个函数. random.random random.random()用于生成一个0到1的随机符点数: 0 < ...
- Python学习笔记之模块与包
一.模块 1.模块的概念 模块这一概念很大程度上是为了解决代码的可重用性而出现的,其实这一概念并没有多复杂,简单来说不过是一个后缀为 .py 的 Python 文件而已 例如,我在某个工作中经常需要打 ...
- Python学习笔记-常用模块
1.python模块 如果你退出 Python 解释器并重新进入,你做的任何定义(变量和方法)都会丢失.因此,如果你想要编写一些更大的程序,为准备解释器输入使用一个文本编辑器会更好,并以那个文件替代作 ...
- Python学习笔记1—模块
模块的使用 引用模块的两种形式 形式一: import module_name 形式二: from module1 import module11 (module11是module的子模块) 例: ...
- Python学习笔记2——模块的发布
1.为模块nester创建文件夹nester,其中包含:nester.py(模块文件): """这是"nester.py"模块,提供了一个名为prin ...
随机推荐
- 单件模式(Singleton)C++实现
意图:保证一个类仅有一个实例,并提供一个访问它的全局访问点. 实用性:1.当类只能有一个实例而且客户可以从一个众所周知的访问点访问它. 2.当这个唯一的实例应该是通过子类可扩展的,并且客户应该无需更改 ...
- 揭秘IPHONE X刷脸认证的技术奥秘
苹果最新发布的Iphone X具有一个全新的功能叫做刷脸认证,背后的技术其实是生物密码的更新,通过人脸识别取代了传统的指纹识别,大家肯定对这种新技术非常感兴趣,下面我们通过这篇文章为大家介绍人脸识别的 ...
- hdu1811 Rank of Tetris 拓扑排序+并查集
这道题是拓扑排序和并查集的综合运用. 由于排行榜是一种从高到低的排序.所以在拓扑排序的时候,如果有一次加入的入度为零的点数大于1,就有变得不确定了(UNCERTAIN). 由于只有一棵树,当树的数量大 ...
- CodeIgniter + smarty 实现widget功能
在开发过程中,经常需要widget功能,一可以隔离页面逻辑,二可以重用代码.结合smarty的plugin功能,可以方便的实现该功能. 譬如,我们的页面中可以这样写: {{extends file=' ...
- 深度学习:又一次推动AI梦想(Marr理论、语义鸿沟、视觉神经网络、神经形态学)
几乎每一次神经网络的再流行,都会出现:推进人工智能的梦想之说. 前言: Marr视觉分层理论 Marr视觉分层理论(百度百科):理论框架主要由视觉所建立.保持.并予以解释的三级表象结构组成,这就是: ...
- 【从零开始】【Java】【2】项目最开始都有什么鬼
闲聊 刨其根知其底. 让我们从一开始就慢嚼细咽. 开始 先来看下项目都有什么: 项目结构图 pom文件图 项目结构 项目=核心代码+依赖管理文件+说明文件+IDE配套文件+外部依赖包: 核心代码:sr ...
- 巧用Ajax的beforeSend提高用户体验
jQuery是经常使用的一个开源js框架,其中的$.ajax请求中有一个beforeSend方法,用于在向服务器发送请求前执行一些动作. $.ajax({ beforeSend:function(){ ...
- Map使用操作系统内存的情况
public static void main(String[] args) { System.out.println("程序启动-->可用内存:"+(getSystemMe ...
- Javascript中的null和 undefined
Javascript Undefined vs NULL Many a times we often get confused on whats the difference between UNDE ...
- 【BZOJ3451】Tyvj1953 Normal - 点分治+FFT
题目来源:NOI2019模拟测试赛(七) 非原题面,题意有略微区别 题意: 吐槽: 心态崩了. 好不容易场上想出一题正解,写了三个小时结果写了个假的点分治,卡成$O(n^2)$ 我退役吧. 题解: 原 ...