当前位置:网站首页>实验五 模块、包和库
实验五 模块、包和库
2022-06-23 21:33:00 【张时贰】
实验五
2022.06.01 下午 实验
实验五 模块、包和库
前言
本文章是 【Python语言基础】 专栏的文章,主要是上课的随堂笔记与练习
Python专栏 传送门
实验源码已在Github整理
题目一
使用Datetime模块获取当前时间,并指出当前时间的年、月、日、周数,以及当天是该周的第几天
问题分析
利用datetime().now获取当前年月日
利用one_time保存当月一号时间, strftime(‘%W’)即可获得当日在本年的第几周,二者相减+1就是周数
当天是该周的第几天:datetime.now().weekday()或者datetime.now().strftime(’%w’)获得周数
代码
""" @Author:张时贰 @Date:2022年06月01日 @CSDN:张时贰 @Blog:zhangshier.vip """
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返回在本周的天数
结果

题目二
使用Random模块和Numpy库生成一个3行4列的多维数组,数组中的每个元素为1~100之间的随机整数,然后求该数组所有元素的平均值
问题分析
利用np.random.randint(范围,范围,(行,列))生成1~1003行4列的多维数组
代码
""" @Author:张时贰 @Date:2022年06月01日 @CSDN:张时贰 @Blog:zhangshier.vip """
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)
结果

题目三
使用Matplotlib库绘制y=2x+1和y=x2 的图形,并设置坐标轴的名称和图列
问题分析
利用numpy定义x范围在1~50,用Matplotlib库,plot(函数,颜色,粗细)定义函数,legend()定义图例
代码
""" @Author:张时贰 @Date:2022年06月01日 @CSDN:张时贰 @Blog:zhangshier.vip """
# 可以输出结果即可,红色报错是库的问题
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:zhangshier.vip """
# 需要的库
# pip install wordcloud
# pip install jieba
# pip install imageio
# 在代码目录下新建一个txt文本,Experiment 5.4_open.txt:党的十八大提出,倡导富强、民主、文明、和谐,倡导自由、平等、公正、法治,倡导爱国、敬业、诚信、友善,积极培育和践行社会主义核心价值观。富强、民主、文明、和谐是国家层面的价值目标,自由、平等、公正、法治是社会层面的价值取向,爱国、敬业、诚信、友善是公民个人层面的价值准则,这24个字是社会主义核心价值观的基本内容。
# 准备一张背景图,修改38行,WordCloud会去除白色部分作为轮廓
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)
# Experiment 5.4_out.txt保存分词结果
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)
# 生成云图 Experiment 5.4_outphoto.png
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)导入库,然后调用并测试
代码
#Experiment_5_test.py
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())
结果

边栏推荐
- Spend small money to do big things: cloud function + cloud development leverages the practice of e-commerce promoting flexible architecture in CCTV evening party
- Elegant asynchronous programming version answer async and await parsing
- Uniapp routing page Jump
- MySQL advanced development
- I am 30 years old, no longer young, and have nothing
- High quality "climbing hand" of course, you have to climb a "high quality" wallpaper
- Encryption and decryption analysis of returned data of an e-commerce app (IV)
- 【Redis】有序集合的交集与并集
- 同花顺开户是安全的吗?
- JS to get the screen size, current web page and browser window
猜你喜欢

嵌入式开发:嵌入式基础——重启和重置的区别

发现一个大佬云集的宝藏硕博社群!

New SQL syntax quick manual!

数据可视化之:没有西瓜的夏天不叫夏天

Beitong G3 game console unpacking experience. It turns out that mobile game experts have achieved this

Uncover the secrets of Huawei cloud enterprise redis issue 16: acid'true' transactions beyond open source redis

Outlook开机自启+关闭时最小化

How PMO uses two dimensions for performance appraisal

Facing the problem of lock waiting, how to realize the second level positioning and analysis of data warehouse
![Harmonyos application development -- mynotepad[memo][api v6] based on textfield and image pseudo rich text](/img/b1/71cc36c45102bdb9c06e099eb42267.jpg)
Harmonyos application development -- mynotepad[memo][api v6] based on textfield and image pseudo rich text
随机推荐
Is it safe to open an online securities account or to go to the business department
The use of go unsafe
How to define an "enumeration" type in JS
个税怎么算?你知道吗
How to make a label for an electric fan
Go language limits the number of goroutines
From AIPL to grow, talking about the marketing analysis model of Internet manufacturers
Common commands for cleaning up kubernetes cluster resources
Go language core 36 lectures (go language practice and application 27) -- learning notes
Spend small money to do big things: cloud function + cloud development leverages the practice of e-commerce promoting flexible architecture in CCTV evening party
Chrome extension development Chinese tutorial-1
Lightweight, dynamic and smooth listening, hero earphone hands-on experience, can really create
Arouter framework analysis
Global and Chinese market for hydropower plants 2022-2028: Research Report on technology, participants, trends, market size and share
What is a database index? Xinhua dictionary to help you
Prometheus primary body test
Using clion to realize STM32F103 lighting LED
Shanghai benchmarking enterprise · Schneider Electric visited benchmarking learning lean production, smart logistics supply chain and digital transformation
[JS 100 examples of reverse] anti climbing practice platform for net Luozhe question 5: console anti debugging
Talk about how to customize data desensitization