模块、包和库
实验目的
(1)了解模块、包、库的概念、区别和联系。
(2)掌握常用标准库模块的功能和使用方法。
(3)掌握常用第三方库的功能和使用方法。
(4)掌握自定义模块的创建和使用方法。
实验内容
1、使用Datetime模块获取当前时间,并指出当前时间的年、月、日、周数,以及当天是该周的第几天?
"""
@Author:*Melon
@Date:2022.11.25
@CSDN:*Melon
"""
from datetime import datetime
now_time = datetime.now() # 当前时间
one_time = now_time.replace(day=1, hour=0, minute=0, second=0, microsecond=0) # 置当月一号
week_num = int(now_time.strftime('%W')) - int(one_time.strftime('%W')) + 1 # now-本月第一周+1=当前周数 strftime('%W')本年第几周
print(f"第{week_num}周")
print(f"{now_time.year}年{now_time.month}月{now_time.day}日")
print(f"该周的第{datetime.now().weekday() + 1}天") # weekday返回0~6所以+1
print(f"该周的第{datetime.now().strftime('%w')}天") # strftime返回在本周的天数
2、使用Random模块和Numpy库生成一个3行4列的多维数组,数组中的每个元素为1~100之间的随机整数,然后求该数组所有元素的平均值。
"""
@Author:*Melon
@Date:2022.11.25
@CSDN:*Melon
"""
import numpy as np
a = np.random.randint(1, 100, (3, 4)) # 1~100 三行四列数组
print(a)
sum = 0
for i in range(3):
for j in range(4):
sum += a[i][j]
average = sum / 12
print("平均数为: %.2f" % average)
3、使用Matplotlib库绘制y=2x+1和y=x2 的图形,并设置坐标轴的名称和图列。
"""
@Author:*Melon
@Date:2022.11.25
@CSDN:*Melon
"""
# 可以输出结果即可,红色报错是库的问题
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1, 50)
plt.plot(x, 2 * x + 1, 'red', lw=2)
plt.plot(x, x ** 2, 'b', linestyle='dashed', lw=2)
plt.legend(['2*x+1', 'x**2']) # 设置图例
plt.show()
4、编写一个程序,实现对一篇中文文章进行分词和统计,结果使用词云图展示。
"""
@Author:*Melon
@Date:2022.11.25
@CSDN:*Melon
"""
# 4、编写一个程序,实现对一篇中文文章进行分词和统计,结果使用词云图展示。
import jieba
import imageio.v2 as imageio
from wordcloud import WordCloud
with open("4.txt", "r", encoding='UTF-8') as f:
allSentence = f.read()
print(allSentence)
re_move = [',', '。', '\n', '\xa0', '-', '(', ')'] # 无效数据
# 去除无关数据
for i in re_move:
allSentence = allSentence.replace(i, "")
pureWord = jieba.lcut(allSentence)
# 4.txt保存分词结果
with open("4.txt", "w") as f:
for i in pureWord:
f.write(str(i) + " ")
with open("4.txt", "r") as f:
pureWord = f.read()
mask = imageio.imread("4.png")
word = WordCloud(background_color="white",
width=800, height=800,
font_path='宋体粗体.ttf',
mask=mask, ).generate(pureWord)
# 生成云图 4.png
word.to_file('4*.png')
5、自定义一个模块,然后在其他源文件中进行调用、测试。
"""
@Author:*Melon
@Date:2022.11.25
@CSDN:*Melon
"""
# 5、自定义一个模块,然后在其他源文件中进行调用、测试。
# 别名
import test5 as test
print(test.func_test())
# 直接导库
import test5
print(test5.func_test())
def func_test():
return '测试5模块中的func_test()函数'