当前位置:网站首页>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

边栏推荐
- [同源策略 - 跨域问题]
- How to batch generate UPC-A codes
- 发现一个大佬云集的宝藏硕博社群!
- How to create cloud disk service how to create cloud disk service backup?
- Salesforce heroku (IV) application in salesforce (connectedapp)
- How to make a label for an electric fan
- Infrastructure splitting of service splitting
- Find my information | Apple may launch the second generation airtag. Try the Lenz technology find my solution
- Data visualization: summer without watermelon is not summer
- HR SaaS is finally on the rise
猜你喜欢

How to calculate individual income tax? You know what?

Embedded development: embedded foundation -- the difference between restart and reset

Minimisé lorsque Outlook est allumé + éteint

个税怎么算?你知道吗

Simple code and design concept of "back to top"
![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

How PMO uses two dimensions for performance appraisal

Find my information | Apple may launch the second generation airtag. Try the Lenz technology find my solution

Four aspects of PMO Department value assessment

Cloud native practice of meituan cluster scheduling system
随机推荐
Do you really understand the cache penetration, cache breakdown and cache avalanche in rotten street?
Analysis of visual analysis technology
Prometheus primary body test
Lighthouse open source application practice: snipe it
Wechat smart operation 3.0+ Alipay digital transformation 3.0
Selenium batch query athletes' technical grades
ZABBIX custom monitoring item (server monitoring)
How to calculate individual income tax? You know what?
Harmonyos application development -- mynotepad[memo][api v6] based on textfield and image pseudo rich text
Who do you want to open a stock account? Is it safe to open an account online?
[js] 生成随机数组
What are the main dimensions of PMO performance appraisal?
Open source C # WPF control library --newbeecoder UI usage guide (III)
2021-12-25: given a string s consisting only of 0 and 1, assume that the subscript is from
What are the advantages of attaching a virtual machine to a hard disk cloud server
HDLBits->Circuits->Arithmetic Circuitd->3-bit binary adder
Drawing STM32 minimum system schematic diagram with AD
Chrome extension development Chinese tutorial-1
Improve efficiency, take you to batch generate 100 ID photos with QR code
小程序ssl证书过期是什么原因导致的?小程序ssl证书到期了怎么解决?