实验五
🌴 2022.06.01 下午 实验
实验五 模块、包和库
题目一
使用Datetime模块获取当前时间,并指出当前时间的年、月、日、周数,以及当天是该周的第几天
问题分析
利用datetime().now获取当前年月日
利用one_time保存当月一号时间, strftime(‘%W’)即可获得当日在本年的第几周,二者相减+1就是周数
当天是该周的第几天:datetime.now().weekday()或者datetime.now().strftime(’%w’)获得周数
参考:Python strftime( )函数
代码
""" @Author:张时贰 @Date:2022年06月01日 @CSDN:张时贰 @Blog:zhsher.cn """ 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 print(f"第{week_num}周") print (f"{now_time.year}年{now_time.month}月{now_time.day}日")
print(f"该周的第{datetime.now().weekday()+1}天") print(f"该周的第{datetime.now().strftime('%w')}天")
|
结果

题目二
使用Random模块和Numpy库生成一个3行4列的多维数组,数组中的每个元素为1~100之间的随机整数,然后求该数组所有元素的平均值
问题分析
利用np.random.randint(范围,范围,(行,列))生成1~1003行4列的多维数组
代码
""" @Author:张时贰 @Date:2022年06月01日 @CSDN:张时贰 @Blog:zhsher.cn """ import numpy as np a= np.random.randint(1,100,(3,4)) print(a) sum=0 for i in range(3): for j in range(4): sum+=a[i][j] average=sum/12 print("平均数为: %.2f" %average)
|
结果

题目三
使用Matplotlib库绘制y=2x+1和y=x2 的图形,并设置坐标轴的名称和图列
问题分析
利用numpy定义x范围在1~50,用Matplotlib库,plot(函数,颜色,粗细)定义函数,legend()定义图例
代码
""" @Author:张时贰 @Date:2022年06月01日 @CSDN:张时贰 @Blog:zhsher.cn """
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()
|
结果

题目四
编写一个程序,实现对一篇中文文章进行分词和统计,结果使用词云图展示
问题分析
事先准备好一份测试文件,保存需要处理的数据,以及一张图片作为云图的背景。将文件读入后利用jieba.lcut()对字符串分词,之后通过wordcloud模块生成云图
参考:wordcloud参数详解,巨详细
代码
""" @Author:张时贰 @Date:2022年06月01日 @CSDN:张时贰 @Blog:zhsher.cn """
import jieba import imageio.v2 as imageio from wordcloud import WordCloud
with open("Experiment 5.4_open.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)
with open("Experiment 5.4_out.txt", "w") as f: for i in pureWord: f.write(str(i)+" ")
with open("Experiment 5.4_out.txt", "r") as f: pureWord = f.read()
mask = imageio.imread("Experiment 5.4_bg.png") word = WordCloud(background_color="white", width=800,height=800, font_path='simhei.ttf', mask=mask,).generate(pureWord)
word.to_file('Experiment 5.4_outphoto.png')
|
结果

题目五
自定义一个模块,然后在其他源文件中进行调用、测试
问题分析
在Experiment_5_test.py文件中编写一段函数,在Experiment 5.5.py中通过import Experiment_5_test(或import Experiment_5_test as test)导入库,然后调用并测试
代码
def func_test(): return '测试A55模块中的func_test()函数'
|
import Experiment_5_test as test print(test.func_test())
import Experiment_5_test print(Experiment_5_test.func_test())
|
结果
