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

边栏推荐
- Find My资讯|苹果可能会推出第二代AirTag,试试伦茨科技Find My方案
- [JS 100 examples of reverse] anti climbing practice platform for net Luozhe question 5: console anti debugging
- Connect edgex gateway to thingsboard IOT platform
- Aiot application innovation competition - get better code completion and jump experience with clion
- Dart series: look at me for security. The security feature in dart is null safety
- Tdsql elite challenge CVM voucher usage guide
- HDLBits-> Circuits-> Arithmetic Circuitd-> 3-bit binary adder
- Global and Chinese markets of natural starch 2022-2028: Research Report on technology, participants, trends, market size and share
- Start optimization - directed acyclic graph
- Cloud native practice of meituan cluster scheduling system
猜你喜欢

Minimize outlook startup + shutdown

Find My资讯|苹果可能会推出第二代AirTag,试试伦茨科技Find My方案

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

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

Gradle asked seven times. You should know that~

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

Bluetooth chip | Renesas and Ti launch new Bluetooth chip, try Lenz st17h65 Bluetooth ble5.2 chip

How to calculate individual income tax? You know what?

I am 30 years old, no longer young, and have nothing

蓝牙芯片|瑞萨和TI推出新蓝牙芯片,试试伦茨科技ST17H65蓝牙BLE5.2芯片
随机推荐
Use of pathinfo/pathname in nodejs
Go language core 36 lectures (go language practice and application 27) -- learning notes
What is the use of PMP certification?
Improve efficiency, take you to batch generate 100 ID photos with QR code
ECS (no matter which one, as long as it is an ordinary ECS) uses the installed version of SketchUp to install an error
[js] 生成随机数组
Embedded development: embedded foundation -- the difference between restart and reset
Connect edgex gateway to thingsboard IOT platform
实验五 模块、包和库
Those programmers wrote super funny 56 code comments (worth collecting)!!
What is the process of opening a mobile card account? Is online account opening safe?
How many of the five app automated test AIDS have you used?
To develop AI face comparison, how to output multiple faces with comparative similarity?
How to create cloud disk service how to create cloud disk service backup?
Markdown syntax summary
Global and Chinese market of gas fire pit 2022-2028: Research Report on technology, participants, trends, market size and share
Simple code and design concept of "back to top"
Raid card with hardware knowledge (5)
How to download offline versions of Firefox and chrome
Go bubbling, cocktail, quick, insert sort