导入模块的几种情况:
from 模块名 import 变量/类/函数
import 模块名
import 模块名 as 对模块命名
from 模块名 import * 可以用所有的模块的函数
from 模块名 import 函数/类/变量 as 别名
random模块
randint(a,b) [a, b] 之间的随机数
random() 用来输出[0, 1)的随机数
randrange(a, b) [a, b)之间的随机数
choice 随机选择一个数字可以用列表,元组
sample 随机选取(自己设置)几个数字一般在列表,元组
shuffle 打散列表
import random
# randint(a,b) [a, b] 之间的随机数
print(random.randint(0,2)) 1
# random() 用来输出[0, 1)的随机数
print(random.random()) 0.12419153483579881
# randrange(a, b) [a, b)之间的随机数
print(random.randrange(1, 9)) 2
# choice 随机选择一个数字可以用列表,元组
print(random.choice([1,2,3,4,5,6,7,8,9,12,31,14])) 5
print(random.choice((1,2,3,4,5,6,7,8,9,0))) 1
#sample 随机选取(自己设置)几个数字一般在列表,元组
print(random.sample([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17], 3)) [4, 7, 3]
print(random.sample((1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17), 5)) [6, 11, 8, 17, 1]
#shuffle 打散列表
x = [1,2,3,4,5,6,7,8,9]
random.shuffle(x)
print(x) [3, 9, 5, 7, 6, 8, 2, 4, 1]
math 模块
floor 向下取整
ceil 向上取整
factorial 阶乘
pow 幂函数
sqrt 返回平方根
pi ——— Π
sin
cos
tan
log10 以10为底
log2 以2为底
log1p 以e为底
fabs 返回绝对值
exp 返回以e为底的函数
exp2 返回以2为底的函数
import math
print(math.floor(1.655)) 1
print(math.ceil(1.333)) 2
print(math.sqrt(4)) 2.0
print(math.pow(2,3)) 8.0
print(math.factorial(3)) 6
print(math.pi) 3.141592653589793
print(math.sin(math.pi * 45 / 180)) # 45度 math.pi * 45 / 180 0.7071067811865476
print(math.cos(math.pi * 30 / 180)) 0.8660254037844387
print(math.tan(math.pi * 90 /180)) 1.633123935319537e+16
print(math.log10(100)) 2.0
print(math.log2(100)) 6.643856189774724
print(math.log1p(100)) 4.61512051684126
print(math.exp(2)) 7.38905609893065
print(math.exp2(3)) 8.0
os 模块
../ 返回上一层文件
./ 当前文件夹
path是路径
os.path
os.path.dirname(__file__) 获取当前文件所在的文件目录
os.path.isabs(path) 判断是否是绝对路径
os.path.abspath(path) 判断当前文件是否是绝对路径
os.path.join(path, "a1.jpg") 拼接path地址和a1.jpg的文件
os.path.isfile(path) 判断是否是文件
os.path.isdir(path) 判断是否是文件夹
os.path.split(path) 将最后一个文件和文件的地址分开
os.path.splitext(path) 将文件和后缀名分开
os.path.getsize(path) 获取文件的大小,单位字节
os.path.exist(path) 判断文件是否存在
os.getcwd() 获取当前文件所在的文件目录
os.mkdir(path) 创建文件夹
os.rmdir(path) 删除文件夹,只能删除空文件
os.removedirs(path) 删除空目录
os.remove(path) 删除文件
os.chdir() 切换文件相当于cd
time 模块
time.time() 1970-01-01 00:00:00 到现在的时间
time.sleep(secs) secs 停止秒数 停止几秒
time.ctime(second) second 返回时间为星期,月份,日期
time.asctime() 返回当前的时间
time.strftime("%Y-%m-%d %H:%M:%d") 返回当前时间的 年 月 日 小时 分钟 秒
time.gmtime()
import time
print(time.time())
time.sleep(2)
print(time.ctime(1714493678.466593)) # Wed May 1 00:14:38 2024
print(time.asctime()) # Wed May 1 00:24:21 2024
print(time.strftime("%Y-%m-%d %H:%M:%d")) # 2024-05-01 14:55:01
print(time.gmtime()) time.struct_time(tm_year=2024, tm_mon=5, tm_mday=1, tm_hour=6, tm_min=52, tm_sec=22, tm_wday=2, tm_yday=122, tm_isdst=0)
turtle 模块
设置画布大小:
screensize(canvwidth,canvheight,bg) 设置宽,高,背景
setup(width,height,startx,starty) 设置宽,高,左上角顶点位置
pensize() 画笔的宽度,数字越大,画笔越粗
pencolor() 设置画笔的颜色
penup() 提前画笔
pendown() 放下画笔
forward(distance) 向画笔方向,移动distance个像素
backword(distance) 像画笔相反的方向移动distance个像素
right(degree) 顺时针转degree角度
left(degree) 逆时针转degree角度
goto(x, y) 画笔移动到(x, y)指定的位置
setx(x) 将画笔移动当前x轴的指定位置
sety(y) 将画笔移动当前y轴的指定位置
circle() #画圆,正(左),负(右)
home() #画笔返回原点,画笔指向右侧
setheading(angle) #设置当前朝向angle的角度
dot(r, color)
fillcolor(coloring) #绘制填空的颜色
color(color1, color2) #第一个参数设置pensize的颜色, 第二个参数为填充的颜色
begin_fill() #开始填充图像
end_fill() #结束填充
hidetutle() #隐藏画笔turtle的形状
showturtle() #显示turtle的形状
done() #使绘图窗口不会消失
clear() #清除turtle窗口,但位置和状态不变
reset() #清除窗口,重置turtle状态为起始状态
undo() #撤销上一个turtle动作
isvisible() #返回当前turtle是否可见
stampe() #复制当前图像
write(arg: object, move: bool = ..., align: str = ..., font: tuple[str, int, str] = ...)
datatime模块
now 当前时间
date(year, month, day) 创建日期
time(hour, minute, second, millisecond) 创建时间
datetime.datetime.now() + timedalta(3) 三天后的时间
datetime.time.hour 小时对象
datetime.data.ctime()
datetime.date.today() 今天的时间
datetime.timedelta() 设置几天时间
datetime.datetime.now() 返回现在的时间
import turtle,time
def drawgap(): #绘制数码管间隔
turtle.penup()
turtle.fd(5)
def drawline(draw): #绘制单段数码管
drawgap()
turtle.pendown() if draw else turtle.penup()
turtle.fd(40)
drawgap()
turtle.right(90)
def drawdigit(digit): #根据数字绘制七段数码管
drawline(True) if digit in [2,3,4,5,6,8,9] else drawline(False)
drawline(True) if digit in [0,1,3,4,5,6,7,8,9] else drawline(False)
drawline(True) if digit in [0,2,3,5,6,8,9] else drawline(False)
drawline(True) if digit in [0,2,6,8] else drawline(False)
turtle.left(90)
drawline(True) if digit in [0,4,5,6,8,9] else drawline(False)
drawline(True) if digit in [0,2,3,5,6,7,8,9] else drawline(False)
drawline(True) if digit in [0,1,2,3,4,7,8,9] else drawline(False)
turtle.left(180)
turtle.penup()
turtle.fd(20)
def drawdate(date): #data为日期,格式为'%Y-%m=%d+'
turtle.pencolor("red")
for i in date:
if i == '-':
turtle.write('年',font=("Arial",24,"normal"))
turtle.pencolor("green")
turtle.fd(40)
elif i == '=':
turtle.write('月',font=("Arial",24,"normal"))
turtle.pencolor("blue")
turtle.fd(40)
elif i == '+':
turtle.write('日',font=("Arial",24,"normal"))
else:
drawdigit(eval(i))
def main():
turtle.setup(800,350,200,200)
turtle.penup()
turtle.fd(-300)
turtle.pensize(5)
drawdate(time.strftime('%Y-%m=%d+',time.gmtime()))
turtle.hideturtle()
turtle.done()
main()
calendar模块
calendar.calendar(theyear, w, l, c, m) 打印日期
calendar.isleap() 判断是否是闰年
calendar.leapdays() 判断两个年份之间存在多少个闰年
calendar.month() 打印一个月份
import calendar
print(calendar.calendar(2024)) # 打印2024年1~12月的日期
print(calendar.month(2024,5)) #打印2024年五月的日期
print(calendar.isleap(2024)) #判断2024年是否是闰年 True
print(calendar.leapdays(1000,2000)) #1000~2000年有242个闰年
# 判断是否是闰年 闰年判断:能被4整除,不能被100整除,但能被400整除
def is_leap_year(x, y):
for year in range(x, y):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(year,end = "\t")
x = int(input("请输入年份:"))
y = int(input("请输入年份:"))
is_leap_year(x, y)
copy模块
copy.copy()
1、浅拷贝(Shallow Copy):当一个对象被浅拷贝时,如果这个对象中包含其他对象,
那么这些被包含的对象不会被创建新的副本,而是仍然指向原来的对象。因此,修改这个
拷贝出来的对象时,原始对象中的相应对象也会被修改
copy.deepcopy()
2、深拷贝(Deep Copy):当一个对象被深拷贝时,如果这个对象中包含其他对象,
那么这些被包含的对象会被创建新的副本。因此,修改这个拷贝出来的对象时,原始
对象中的相应对象不会受到影响
import copy
original_list = [1, 2, [3, 4], 5]
shallow_copy = copy.copy(original_list)
print("原始列表:",original_list)
print("浅拷贝:",shallow_copy)
shallow_copy[2][0] = 'a'
print("原始列表:",original_list)
'''
原始列表: [1, 2, [3, 4], 5]
浅拷贝: [1, 2, [3, 4], 5]
原始列表: [1, 2, ['a', 4], 5]
'''
deep_copy = copy.deepcopy(original_list)
print("原始列表:",original_list)
print("浅拷贝:",deep_copy)
deep_copy[2][0] = 'a'
print("原始列表:",original_list)
'''
原始列表: [1, 2, [3, 4], 5]
浅拷贝: [1, 2, [3, 4], 5]
原始列表: [1, 2, [3, 4], 5]
'''
jieba 模块 对中文分词
lcut(s, cut_all = True) 把字符串转化为列表的词组,返回一个迭代对象为分词的迭代对象
lcut(s) 把字符串传化为列表的词组
add_word(w) 向分词词典中增加新词w
cut(s) 返回一个迭代对象为分词的迭代对象
cut(s, cut_all = True) 返回一个迭代对象为分词的迭代对象,返回一个迭代对象为分词的迭代对象
cut_for_search(s) 搜索引擎模式,搜索适合的分词,是一个迭代对象
import jieba
china = "我是一个中国人"
print(jieba.lcut(china)) # ['我', '是', '一个', '中国', '人']
print(jieba.lcut(china, cut_all = True)) # ['我', '是', '一个', '中国', '国人']
s = "中国人民共和国是一个伟大的民族,始终屹立在世界之颠"
print(jieba.lcut(s)) # ['中国', '人民共和国', '是', '一个', '伟大', '的', '民族', ',', '始终', '屹立', '在', '世界', '之颠']
print(jieba.lcut(s, cut_all = True)) # ['中国', '国人', '人民', '人民共和国', '共和', '共和国', '国是', '一个', '伟大', '的', '民族', ',', '始终', '屹立', '在世', '世界', '之', '颠']
jieba.add_word("中国人民共和国")
print(jieba.lcut(s)) # ['中国人民共和国', '是', '一个', '伟大', '的', '民族', ',', '始终', '屹立', '在', '世界', '之颠']
print(jieba.cut(s)) # <generator object Tokenizer.cut at 0x000002388A236980>
for i in jieba.cut(s):
print(i,end = "\t") # 中国人民共和国 是 一个 伟大 的 民族 , 始终 屹立 在 世界 之颠
print("\n",jieba.cut_for_search(s)) # <generator object Tokenizer.cut_for_search at 0x0000024ACEF98EE0>
print(list(jieba.cut_for_search(s))) #['中国', '国人', '人民', '共和', '共和国', '中国人民共和国', '是', '一个', '伟大', '的', '民族', ',', '始终', '屹立', '在', '世界', '之颠']
import jieba
txt = open("D:\luwenfeng\三国演义.txt", "r", encoding = "utf-8").read()
words = jieba.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("{} : {}".format(word, count))