当前位置:网站首页>Experiment 5 module, package and Library
Experiment 5 module, package and Library
2022-06-23 21:42:00 【Zhangshier】
Experiment five
2022.06.01 Afternoon experiment
Experiment five modular 、 Baoheku
List of articles
Preface
This article is 【Python Language foundation 】 Column articles , Mainly the notes and exercises in class
Python special column Portal
The experimental source code has been in Github Arrangement
Topic 1
Use Datetime Module gets the current time , And indicate the year of the current time 、 month 、 Japan 、 Weeks , And the day is the day of the week
Problem analysis
utilize datetime().now Get the current date
utilize one_time Save the first day of the current month , strftime(‘%W’) You can get the current day in the week of the year , The two are subtractive +1 It's the number of weeks
That day is the day of the week :datetime.now().weekday() perhaps datetime.now().strftime(’%w’) Get weeks
Reference resources :Python strftime( ) function
Code
""" @Author: Zhang Shier @Date:2022 year 06 month 01 Japan @CSDN: Zhang Shier @Blog:zhangshier.vip """
from datetime import datetime
now_time = datetime.now () # current time
one_time = now_time.replace(day=1, hour=0, minute=0, second=0, microsecond=0) # Set the first day of the month
week_num=int(now_time.strftime('%W')) - int(one_time.strftime('%W'))+1 # now- The first week of this month +1= Current weeks strftime('%W') What week of the year
print(f" The first {
week_num} Zhou ")
print (f"{
now_time.year} year {
now_time.month} month {
now_time.day} Japan ")
print(f" Day of the week {
datetime.now().weekday()+1} God ") # weekday return 0~6 therefore +1
print(f" Day of the week {
datetime.now().strftime('%w')} God ") # strftime Returns the number of days in the week
result

Topic two
Use Random Module and Numpy The library generates a 3 That's ok 4 Multidimensional array of columns , Each element in the array is 1~100 Random integer between , Then find the average of all the elements of the array
Problem analysis
utilize np.random.randint( Range , Range ,( That's ok , Column )) Generate 1~1003 That's ok 4 Multidimensional array of columns
Code
""" @Author: Zhang Shier @Date:2022 year 06 month 01 Japan @CSDN: Zhang Shier @Blog:zhangshier.vip """
import numpy as np
a= np.random.randint(1,100,(3,4)) #1~100 Three row and four column array
print(a)
sum=0
for i in range(3):
for j in range(4):
sum+=a[i][j]
average=sum/12
print(" The average is : %.2f" %average)
result

Topic three
Use Matplotlib Library drawing y=2x+1 and y=x2 The graphic , And set the name of the coordinate axis and the diagram column
Problem analysis
utilize numpy Definition x The scope is 1~50, use Matplotlib library ,plot( function , Color , thickness ) Defined function ,legend() Define legend
Code
""" @Author: Zhang Shier @Date:2022 year 06 month 01 Japan @CSDN: Zhang Shier @Blog:zhangshier.vip """
# You can output the results , The red error report is a problem with the database
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']) # Set legend
plt.show()
result

Topic four
Write a program , Realize word segmentation and statistics of a Chinese article , The results are displayed by word cloud
Problem analysis
Prepare a test file in advance , Save the data to be processed , And a picture as the background of the cloud picture . Read in the file and use jieba.lcut() Word segmentation for strings , After through wordcloud The module generates a cloud map
Reference resources :wordcloud Parameters, , Great detail
Code
""" @Author: Zhang Shier @Date:2022 year 06 month 01 Japan @CSDN: Zhang Shier @Blog:zhangshier.vip """
# Required libraries
# pip install wordcloud
# pip install jieba
# pip install imageio
# Create a new... In the code directory txt Text ,Experiment 5.4_open.txt: The 18th National Congress of the Communist Party of China proposed , Advocate prosperity 、 democracy 、 civilization 、 harmonious , Advocate freedom 、 equality 、 justice 、 The rule of law , Advocate patriotism 、 dedicated 、 The good faith 、 friendly , Actively cultivate and Practice Socialist Core Values . Rich and strong (powerful) 、 democracy 、 civilization 、 Harmony is the value goal at the national level , free 、 equality 、 justice 、 The rule of law is the value orientation at the social level , patriotic 、 dedicated 、 The good faith 、 Friendliness is the value criterion at the individual level of citizens , this 24 One word is the basic content of the socialist core values .
# Prepare a background image , modify 38 That's ok ,WordCloud The white part will be removed as the outline
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', '-', '(', ')'] # Invalid data
# Remove irrelevant data
for i in re_move:
allSentence = allSentence.replace(i, "")
pureWord = jieba.lcut(allSentence)
# Experiment 5.4_out.txt Save word segmentation results
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)
# Generate cloud map Experiment 5.4_outphoto.png
word.to_file('Experiment 5.4_outphoto.png')
result

Topic 5
Customize a module , Then make calls in other source files 、 test
Problem analysis
stay Experiment_5_test.py File to write a function , stay Experiment 5.5.py Pass through import Experiment_5_test( or import Experiment_5_test as test) Import library , Then call and test
Code
#Experiment_5_test.py
def func_test():
return ' test A55 Module func_test() function '
# Alias
import Experiment_5_test as test
print(test.func_test())
# Direct import library
import Experiment_5_test
print(Experiment_5_test.func_test())
result

边栏推荐
- Facing the problem of lock waiting, how to realize the second level positioning and analysis of data warehouse
- ZABBIX custom monitoring item (server monitoring)
- Using clion to realize STM32F103 lighting LED
- 股票开户要找谁?网上开户安全么?
- The new track of flagship chip is finally clear
- 我在深圳,到哪里开户比较好?在线开户安全么?
- Troubleshooting the problem that the channel cannot play after easycvr cascades to the upper platform
- Teach you to turn the web page into Exe file (super simple)
- ES6 promise detailed sewing Red Treasure Book Introduction to ES6 standard
- Outlook开机自启+关闭时最小化
猜你喜欢

实验五 模块、包和库

大一女生废话编程爆火!懂不懂编程的看完都拴Q了

Lightweight, dynamic and smooth listening, hero earphone hands-on experience, can really create

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

Facing the problem of lock waiting, how to realize the second level positioning and analysis of data warehouse

微信小程序中发送网络请求

Minimisé lorsque Outlook est allumé + éteint

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

How to calculate individual income tax? You know what?

Selenium batch query athletes' technical grades
随机推荐
Is PMP necessary?
我在深圳,到哪里开户比较好?在线开户安全么?
Initial experience of nodejs express framework
Aiot application innovation competition - get better code completion and jump experience with clion
Retrofit magic, reject duplicate code!
Open source C # WPF control library --newbeecoder UI User Guide (II)
Find My资讯|苹果可能会推出第二代AirTag,试试伦茨科技Find My方案
How to reduce snapshots
Global and Chinese market of gas fire pit 2022-2028: Research Report on technology, participants, trends, market size and share
Lightweight, dynamic and smooth listening, hero earphone hands-on experience, can really create
Go language limits the number of goroutines
[redis] intersection and union of ordered sets
【Proteus仿真】LCD1602+DS1307按键设置简易时钟
How to view the role of PMO in agile organizations?
同花顺股票开户是安全的吗?
A detailed discussion on the use guide of network Swiss Army knife nmap
Analysis of a series a e-commerce app docommandnative
ECS (no matter which one, as long as it is an ordinary ECS) uses the installed version of SketchUp to install an error
Using clion to realize STM32F103 lighting LED
Improve efficiency, take you to batch generate 100 ID photos with QR code