time库和datetime库
time库
是处理时间的标准库,可用于程序性能分析
时间获取
time() 获取当前时间戳,浮点数 1970.1.1 00.00开始
ctime() 获取当前时间并且以一种易读时间的函数
gmtime() 生成的一种计算机可以处理的格式
时间格式化
strftime(tpl,ts) tpl是格式化模板字符串,用来定义输出效果 ts是计算机内部时间类型变量
strptime(str,tpl) 将一个字符串定义成计算机内部可以操作的时间
格式化字符串
- %Y 年份 0000~9999
- %m 月份 01~12
- %B 月份名称 如April
- %b 月份名称缩写 如Apr
- %d 日期 01~31
- %A 星期 全写
- %a 星期 缩写 Sun
- %H 小时 00~23
- %h 小时 01~12
- %p 上午下午标识符 AM,PM
- %M 分钟 00~59
- %S 秒 00~59
程序计时
sleep(s) 让程序休眠s秒
perf_counter() CPU 级别的精确值数值,用差值来表达准确用时,调用两次,其差为所用时间
实例操作打印文本进度条
单行动态刷新条:
- 刷新的本质是:用打印后的字符覆盖之前的字符
- 不能换行:print()需要被控制。默认print会自动换行
- 要能回退:打印后光标退回到之前的位置\r
实例:
#TextProBarV1.py
import time
for i in range(101):
print("\r{:3}%".format(i),end="")
time.sleep(0.1)
datetime库
from datetime import datetime
from datetime import timedelta
1) 获取当前日期和时间
today = datetime.today() # 返回当前时间时分秒都为0
print(“当前时间”)
print(today)
today1 = datetime.now() # 返回当前日期和时间
now.hour # 时
now.minute # 分
now.isoweekday()# 返回的1-7代表周一--周日;
now.weekday()# 返回的0-6代表周一--到周日标准格式中%w 1-6表示周一--周六,0代表周日
print( today1 )
today2 = datetime.utcnow() # 返回当前东八区时间就是比当时时间少8个小时
print(today2)
2) 获取指定日期和时间,加减计算
time= datetime(2019, 5, 12, 12, 13, 14)
d= time + timedelta(weeks=0, days=0, hours=0, minutes=0, seconds=0, milliseconds=0, microseconds=0, )
#依次为 “周” “天”, “时”,“分”,“秒”,“毫秒”,“微秒”
print(time)
print(d)
time1= “2019-5-12 12:13:14” # 字符串 日期
d1 = datetime.strptime(str(time1),’%Y-%m-%d %H:%M:%S’)
plus= d1 + timedelta(days=1) # 加
minus = d1 - timedelta(days=1) # 减
print(time1)
print(d1)
print(plus)
print(minus )
time2= 20190512121314
d2 = datetime.strptime(str(time2),’%Y%m%d%H%M%S’)
delta = d2 + timedelta(days=1)
print(time2)
print(d2 )
print(delta)
3) 日期datetime-timestamp 时间戳相互转
now_stamp = time.timestamp()
print(‘指定时间对应时间戳 :’, now_stamp)
print(‘对应本地时间 :’, datetime.fromtimestamp(now_stamp ))
print(‘UTC标准时间 :’, datetime.utcfromtimestamp(now_stamp ))
print(‘本周的第几天:’, datetime.fromtimestamp(now_stamp ).weekday())
4) datetime 时间 转换为str字符串
now = datetime.now()
print(‘当前时间 :’, now)
print(now.strftime(’%Y%m%d%H%M%S’))
random库
基本随机数函数:
seed() 不选种子则用计算机系统的时间作为种子,种子相同,随机数序列一样
random() 产生随机数(产生0~1之间的数)
扩展随机数函数:
randint(a,b) 产生[a,b]之间的整数
getrandbits(k) 生成一个k比特的随机整数
uniform(a,b) 生成[a,b]之间的随机小数
randrange(m,n) 生成一个[m,n)之间以k为步长的随机整数
choice(seq) 从序列seq中随机选择一个元素
shuffle(seq) 将序列seq中元素随机排列
实例:
蒙特卡洛模拟计算圆周率
PyInstaller库
可以使得py文件打包生成可执行文件
使用命令行,
pyinstaller -F 文件名
之后就会产生几个文件夹,其他都可以删除,只有一个文件夹(dist)中有一个有用的可执行文件
常用参数:
-h 查看帮助
--clean 清理打包过程中的临时文件
-D --onedir 默认值,生成dist文件夹
-F --onefile 在dist文件夹中只生成独立的打包文件
-i <图标文件名.ico> 指定打包程序使用的图标(icon)文件
OS库
路径操作
os.path子库
etsize(path) 返回path对应文件的大小,以字节为单位
进程管理
os.system(command)
相当于在命令行中进行输入
环境参数
os.getlogin() 获得当前系统登录用户名称
os.cpu_count() 获得当前系统的CPU数量
jieba库
优秀的中文第三方库:用于中文词频统计。
对中文文本进行分词存在三种模式
- 精确模式 把文本精确的且分开,不存在冗余模式
- 全模式 把文本中所有可能的词语都扫描出来,有冗余
- 搜索引擎模式 在精确模式的基,对长词再次切分
常用函数
jieba.lcut(s) 常用即可 精确模式,返回一个列表类型的分词结果
jieba.lcut(s,cut_all=true) 全模式,返回一个列表类型的分词结果,存在冗余
jieba.lcut_for_search(s) 搜索引擎模式,返回一个列表类型的分词结果,存在冗余
jieba.add_word(w) 向分词词典中增加新词w
文本词频统计
from jieba import *
txt = open(‘新时代中国特色社会主义.txt’, ‘r’, encoding=‘utf-8’).read()
words = lcut(txt)
counts = {}
for word in words:
if len\(word\)==1:
continue
else:
counts\[word\] = counts.get\(word, 0\)\+1
items = list(counts.items())
items.sort(key=lambda x: x[1], reverse=True)
for i in range(10):
word, count = items[i]
print("(’{0}’, {1})".format(word, count))
turtle 库
#库引入:import turtle
from turtle import \* (可能发生函数重名)
import 库名 as 想要的库名
turtle画笔控制函数
turtle.penup() #海龟天上飞,画笔轨迹不着墨
turtle.pendown() # 与上对应,成对出现
turtle.pensize(width) 别名 turtle.width(width) #海龟腰围,画笔宽度
turtle.pencolor(color)
#color为颜色字符串(turtle.pencolor(”red“))
或r,g,b值(turtle.pencolor((0.63,0.12,0.65))) //元组类型
运动控制函数
turtle.foreward(d) 别名turtle.fd(d) #海龟走直线,向前走直线,d为距离,可为负数
turtle.circle(r,extent=None) #根据半径r绘制extent角度的弧形(弧度) 圆心默认在海龟左侧距离r处。不给第二个参数,默认一个圆。
方向控制函数
turtle.setheading(angle) 别名 turtle.seth(angle) #改变海龟角度,改变行进方向 angle改变行进方向,海龟走角度。//绝对角度
turtle.left(angle) #相对角度
turtle.rigth(angle) #相对角度
wordcloud库
词云,可视化处理
- wordcloud.WordCloud()代表一个词云
- 可以配置参数,加载文本等
使用方法
首先,创建词云对象。
w=wordcloud.WorldCloud()
- 配置对象参数
- 加载词云文本
- 输出词云文件
方法:
w.generate(txt) 向WorldClound对象中加载文本txt
w,to_file(filename) 将词云输出为图像文件,png或者jpg格式
worldcloud做了哪些事?
1.分割 :以空格分割单词
2.统计:单词出现的次数并过滤
3.字体:根据统计配置字号
4.布局:颜色环境尺寸
哪些参数可以加载?
width 图片宽度
height 图片高度
min__font__size 指定词云中字体最小字号,默认4号
max__font__size 指定词云中最大。。根据高度自动条件
font_step 指定词云中字体字号的步进间隔,默认为1
font_path 指定字体文件的路径,默认None
max_words 词云显示的最大单词数量
stop_words 指定词云的排除词列表,即不显示的单词列表
配置词云的外部整体形状: