0%

Python基础之标准库与第三方库

这里记录着小沈学习在Python过程中遇到的6个重要又有趣的Python标准库与第三方库,分别是turtle库、time库、random库、PyInstaller库、jieba库、wordcloud库。

Turtle库

turtle库是Python语言的标准库之一,是入门级的图形绘制函数库。

1.Turtle的绘图窗体

  • turtle.setup(width,height,startx,starty)

    image-20221026233551447

2.Turtle空间坐标体系及其绘制

  • 绝对坐标turtle. goto(x,y)
image-20221026125555079
  • 相对坐标

    • turtle.circle(r,angle)#画圆

      image-20221026125850598
    • turtle.bk(d)#后退

    • turtle.fd(d)#前进

      image-20221026130100140

3.Turtle角度坐标体系及其角度改变

  • 绝对角度turtle.seth(angle)

    image-20221026130556081
  • 海龟角度

    • turtle.left(angle)

    • turtle.right(angle)

      image-20221026130839885

4.Turtle的RGB色彩模式

  • turtle.colormode(mode)

  • 默认采用小数值,可切换为整数值:

    • mode=1.0:RGB小数值模式
    • mode=255:RGB整数值模式
  • 常用RGB色彩:

    image-20221026131931664

5.画笔控制函数

  • turtle.penup()#将画笔抬起
  • turtle.pendown()#将画笔落下
  • turtle.pensize(width)
  • turtle.pencolor(color)

6.简单示例:爱心绘制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import turtle as t
#绘制准备:画布与画笔设置
t.setup(600,600,200,200)
t.penup()
t.left(90)
t.fd(50)
t.pendown()#以上代码相当于设置绘制的起始位置
t.pensize(10)
t.pencolor("pink")
#正式开始绘制
t.left(30)
t.fd(30)
t.circle(90,200)
t.fd(200)
t.left(80)
t.fd(200)
t.circle(90,200)
t.fd(30)
#绘制结束
t.done()

Time库

time库是Python中处理时间的标准库,能够获取系统时间并格式化输出功能,并提供系统级精确计时功能,用于程序性能分析。

1.时间获取

  • time()

  • ctime()

  • gmtime()

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    import time 
    #获取当前时间戳,即计算机内部时间值,浮点数
    t1=time.time()
    #获取当前时间并以易读的方式表示,返回字符串
    t2=time.ctime()
    #获取当时间时间,表示为计算机可处理的时间格式
    t3=time.gmtime()
    print("运行结果:")
    print(t1)
    print(t2)
    print(t3)

    image-20221026135304443

2.时间格式化

  • strftime(tpl,ts)

  • 其中tpl是格式化模板字符串,用来定义输出效果,ts是计算机内部时间类型变量

  • 格式化字符串:

    image-20221026135931077
    1
    2
    3
    4
    import time
    t=time.gmtime()
    s=time.strftime("%Y-%m-%d %H:%M:%S",t)
    print("运行结果:",s)

    image-20221026140545309

3.程序计时

  • perf_counter()#返回一个CPU级别的精确时间计算值,单位为秒

  • sleep(s)#s是休眠时间,单位是秒,可以是浮点数

    1
    2
    3
    4
    5
    import time
    start=time.perf_counter()
    time.sleep(10)
    end=time.perf_counter()
    print("运行结果:",end-start)

    image-20221026141351592

4.简单示例:文本进度条

1
2
3
4
5
6
7
8
9
10
11
12
13
import time
scale = 50
print("执行开始".center(scale//2, "-"))
start = time.perf_counter()
for i in range(scale+1):
a = '*' * i
b = '.' * (scale - i)
c = (i/scale)*100
dur = time.perf_counter() - start、
#\r表示将光标的位置回退到本行的开头位置
print("\r{:^3.0f}%[{}->{}]{:.2f}s".format(c,a,b,dur),end='')
time.sleep(0.1)
print("\n"+"执行结束".center(scale//2,'-'))

Random库

Random库Python中用于生成随机数的标准库。

1.基本随机函数

  • seed()#设置随机种子,初始化给定的随机数种子,默认为当前系统时间
  • random()#生成一个[0.0,1.0)之间的随机小数

2.扩展随机数函数

  • randint(a,b)#生成一个[a,b]之间的整数
  • randrange(m,n[,k])#生成一个[m,n)之间以k为步长的随机整数
  • getrandbits(k)#生成一个k比特长的随机整数
  • uniform(a,b)#生成一个[a,b]之间的随机小数
  • choice(seq)#从序列seq中随机选择一个元素
  • shuffle(seq)#将序列seq中元素随机排列,返回打乱后的序列
1
2
3
4
5
6
7
8
9
10
11
import random as r
print("运行结果如下:")
print(r.random())
print(r.randint(1,10))
print(r.randrange(10,100,10))
print(r.getrandbits(16))
print(r.uniform(1,10))
print(r.choice([3,4,5,0,2]))
s=[1,2,3,4,5]
r.shuffle(s)
print(s)
image-20221026144825189

3.简单示例:蒙特卡罗方法计算圆周率

1
2
3
4
5
6
7
8
9
10
11
12
13
from random import random
from time import perf_counter
DARTS = 1000*1000
hits = 0.0
start = perf_counter()
for i in range(1, DARTS+1):
x, y = random(), random()
dist = pow(x ** 2 + y ** 2, 0.5)
if dist <= 1.0:
hits = hits + 1
pi = 4 * (hits/DARTS)
print("圆周率值是: {}".format(pi))
print("运行时间是: {:.5f}s".format(perf_counter() - start))

PyInstaller库

PyInstaller库是第三方库,故使用前需额外安装,其官网为:PyInstaller Manual — PyInstaller 5.6.1 documentation。其功能是将.py源代码转换成无需源代码的可执行文件。

  • 简单使用(cmd命令行) pyinstaller -F <文件名.py>

    image-20221026150414312
  • PyInstaller库常用参数

    image-20221026150423289

jieba库

jieba是优秀的中文分词第三方库,需要额外安装。jieba利用一个中文词库,确定中文字符之间的关联概率,中文字符间概率大的组成词组,形成分词结果。

  • jieba.lcuts(s)#精确模式,返回一个列表类型的分词结果
  • jieba.lcuts(s,cut_all=True)#全模式,返回一个列表类型的分词结果,存在冗余
  • jieba.lcut_for_search(s)#搜索引擎模式,返回一个列表类型的分析结果,存在冗余
  • jieba.add_word(w)#向分词词典增加新词w
1
2
3
4
5
6
7
8
import jieba
s="努力是成功的别名"
w="蟒蛇语言"
print("运行结果如下:")
print(jieba.lcut(s))
print(jieba.lcut(s,cut_all=True))
print(jieba.lcut_for_search(s))
jieba.add_word(w)
image-20221026152522008

worldcloud库

worldcloud库是一个生成词云的第三方库。wordcloud.WordCloud()代表一个文本对应的词云,可以根据文本中词云出现的频率等参数绘制词云,词云的绘制形状、尺寸和颜色都可以设定。

1.常规使用方法

  • 步骤1:配置对象参数

    参数 描述
    width 指定词云对象生成图片的宽度,默认400像素
    height 指定词云对象生成图片的高度,默认200像素
    min_font_size 指定词云中字体的最小字号,默认4号
    max_font_size 指定词云中字体的最大字号,根据高度自动调节
    font_step 指定词云中字体字号的步进间隔,默认为1
    font_path 指定字体文件的路径,默认None
    max_words 指定词云显示的最大单词数量,默认200
    stop_words 指定词云的排除词列表,即不显示的单词列表
    mask 指定词云形状,默认为长方形,若更改需要引用imread()函数
    background_color 指定词云图片的背景颜色,默认为黑色
  • 步骤2:加载词云文本

    • w.generate(txt)#向WordCloud对象w中加载文本txt
  • 步骤3:输出词云文件

    • w.to_file(filename)#将词云输出为图像文件,.png或.jpg格式
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    import wordcloud
    #配置对象参数
    w=wordcloud.WordCloud(width=500,height=300,font_path="msyh.ttc",min_font_size=2,max_words=20)
    '''
    #mask的使用示例:
    from scipy.misc import imread
    mk=imread("pic.png")
    w=wordcloud.WordCloud(mask=mk)
    '''
    #加载词云文本
    w.generate("The wordcloud by Python,hello world")
    #输出词云文本
    w.to_file("pywordcloud.png")

    结果如下:

pywordcloud

2.简单示例:生成中文词云

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#导入库
import jieba
import wordcloud

#从文件中读取中文单词并转化为每个单词后面都有一个空格的字符串
f = open("励志.txt", "r", encoding="utf-8")
t = f.read()
f.close()
ls = jieba.lcut(t)
txt = " ".join(ls)

#配置词云对象参数
w = wordcloud.WordCloud(width = 1000,height = 700,background_color = "white",font_path = "msyh.ttc")
#加载词云文本
w.generate(txt)
#输出词云文件按
w.to_file("encourage.png")

结果如下:

grwordcloud

Pillow库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from PIL import Image, ImageFilter

im = Image.open('test.png') #打开一个png图像
w, h = im.size #获取图像尺寸
print('Original image size: %sx%s' % (w, h))
im.show() #显示图片

im.thumbnail((w//2, h//2)) #缩放到50%
print('Resize image to: %sx%s' % (w//2, h//2))
im.show()
im.save('thumbnail.png', 'jpeg') #将缩放后的图像用jpeg格式保存

im2 = im.filter(ImageFilter.BLUR) #应用模糊滤镜
im2.show()
im2.save('bur.jpg', 'jpeg')
欢迎来到ssy的世界