When I was visiting Zhihu two days ago, I saw such a question. What interesting or useful things can Python automated office do?
After reading this question, I think this may be a confusion faced by many people in the workplace. I want to use Python in my work to improve efficiency, but I don't know how to start? Python is becoming more and more popular in the field of automated office, and it will be a trend for Python to do repetitive tasks.
Reading some articles on office automation, I feel that it is more of a list of knowledge, and I don't know what I have read after reading it. In order to learn more, today the editor will take student test scores as an example, teach you to use Python to complete automated office, one-click to generate student score data analysis report (word version), full version code, reply in the background of the public account below :Word , if you are interested in PPT and excel automated office, you can leave a message below.
Prepare data
Without data, there is no way to talk about data analysis reports. GitHub Hot List|5 high-quality Python gadgets, the last one is truly artifact! It was introduced that faker can generate data with one line of code. Today I will use this method.
from faker import Faker
import pandas as pd
#生成数据
fake = Faker('zh_CN')
name = []
sex= []
score1 = []
score2 = []
score3 = []
score4 = []
number = range(1,31)
for _ in range(30):
name.append(fake.simple_profile(sex=None)['name'])
sex.append(fake.simple_profile(sex=None)['sex'])
score1.append(random.randint(40,100))
score2.append(random.randint(40,100))
score3.append(random.randint(40,100))
score4.append(random.randint(200,300))
df = pd.DataFrame({
'学号':number,
'姓名':name,
'性别':sex,
'语文':score1,
'数学':score2,
'英语':score3,
'理综':score4
})
df = df.set_index('学号')
df.to_excel('学生成绩单.xlsx')
Generate analysis report
Exam score breakdown
Core code
p = document.add_paragraph('本次测评,全班共有{}名同学参加考试,其中分数总分排名第一的同学是'.format(len(students.姓名)),style='Heading 3')
p.add_run(str(first_student)).bold = True
p.add_run(',分数为')
p.add_run(str(first_score)).bold = True
p.add_run('.学生考试总体成绩如下')
table = document.add_table(rows=len(students.姓名)+1, cols=6, style='Medium Shading 1 Accent 5')
table.cell(0,0).text = '姓名'
table.cell(0,1).text = '语文'
table.cell(0,2).text = '数学'
table.cell(0,3).text = '英语'
table.cell(0,4).text = '理综'
table.cell(0,5).text = '总分'
for i,(index,row) in enumerate(students.iterrows()):
table.cell(i+1, 0).text = str(row['姓名'])
table.cell(i+1, 1).text = str(row['语文'])
table.cell(i+1, 2).text = str(row['数学'])
table.cell(i+1, 3).text = str(row['英语'])
table.cell(i+1, 4).text = str(row['理综'])
table.cell(i+1, 5).text = str(row['总分'])
result
Summary of exam results
Core code
students['总分'] = students.语文 + students.数学 + students.英语 + students.理综
students.sort_values(by='总分', inplace=True, ascending=False)
students.reset_index(drop=True, inplace=True)
#学生成绩汇总表
ax = students.plot.bar(x='姓名', y=['语文','数学','英语','理综'], stacked=True)
plt.title('学生成绩汇总图', fontsize=16) # fontproperties=font
plt.xlabel('姓名', fontsize=10) # fontproperties=font,
plt.xticks(rotation='45', fontsize=8) # fontproperties=font,
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.tight_layout()
plt.savefig('Part3_data.jpg')
Result display
Performance of each subject
def pie_plot(scores):
ratios=dict()
for subject,subjectScore in scores.items():
ratios[subject]={
}
if subject !='理综':
for category,num in groupby(sorted(subjectScore),splitScore):
ratios[subject][category]= len(tuple(num))
else:
for category,num in groupby(sorted(subjectScore),splitScore_lizong):
ratios[subject][category]= len(tuple(num))
fig ,axs = plt.subplots(2,2)
# 画子图
axs.shape=1,4
for index,subjectData in enumerate(ratios.items()):
plt.sca(axs[0][index])
subjectName,subjectRatio = subjectData
plt.pie(list(subjectRatio.values()),labels=list(subjectRatio.keys()),autopct='%1.1f%%')
plt.xlabel(subjectName)
plt.legend(loc="right",bbox_to_anchor=(1, 0, 0.5, 1))
plt.savefig('Part4_data.jpg')
plt.show()
pie_plot(scores)
Result display
Previous examination results
The above are all data analysis reports for a class as a whole. If you want an analysis report, in addition to analyzing the overall performance of the class, you also want to generate a report for individual performance. The purpose is not only to know the overall learning status of the class, but also to know the learning status of each student. Take a student Wang Huan as an example:
Core code
temp_df = pd.DataFrame({
'历次考试':number,
'姓名':'王欢',
'语文':score1,
'数学':score2,
'英语':score3,
'理综':score4
})
plt.subplot(411)
plt.plot(temp_df['语文'],'y*-',label="语文")
plt.subplot(412)
plt.plot(temp_df['数学'],'b*-')
plt.subplot(413)
plt.plot(temp_df['英语'],'r*-')
plt.subplot(414)
plt.plot(temp_df['理综'])
plt.savefig('Part6_data.jpg')
plt.show()
Result display
A summary analysis of the student's performance
Achievement display
Python automated office, the purpose is to improve efficiency, avoid duplication of labor, and at the same time, it can be tailored to everyone's situation, and it can save time and effort. It is very simple. Because the video is not supported, those who are interested can watch it on the official account!
Recommended reading
- Python combat | One-click export WeChat reading records and notes
- It smells so good! Python can make the drawn pictures move!
- Mosaic becomes HD in seconds, this method called PULSE is on fire
- Make a visual travel strategy, travel after the epidemic
- GitHub Hot List|5 high-quality Python gadgets, the last one is a welfare!
For more exciting content, follow the WeChat public account "Python learning and data mining"
In order to facilitate technical exchanges, this account has opened a technical exchange group. If you have any questions, please add a small assistant WeChat account: connect_we. Remarks: The group is from CSDN, welcome to reprint, favorites, codewords are not easy, like the article, just like it! Thanks