绘图 matplotlib.pyplot

设置中文字体

1
2
3
4
5
import matplotlib.pyplot as plt
from pylab import mpl

# 设置显示中文字体
mpl.rcParams["font.sans-serif"] = ["SimHei"]

保存高清大图

1
plt.savefig('result.png', dpi=500, bbox_inches='tight')

文件操作 pandas

1
import pandas as pd

操作csv

1
2
# header 是否有表头
pd.read_csv('./data/read/num_place_dict.csv', encoding='utf-8', header=None)

1
2
# index 是否显示索引	header 是否显示表头
df.to_csv('./data/history/history_data.csv', mode='a', index=False, header=False, encoding='utf-8')

操作 DataFrame

选择行列.iloc

1
data.iloc[选择的行, 选择的列]

按指定规则添加一列

1
2
3
4
5
# 求DataFrame中某几列的总和
def func(data):
return data['政治'] + data["英语"] + data["专业课"] + data["高等数学"]
data = data.astype('object') # 如报错时添加这句
data["总分"] = data.apply(get_total, axis=1)

爬虫 requests & bs4

请求头 header

  • 注意是否需要cookie字段,如需要,可以利用chrome浏览器获取
1
2
3
headers = {
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36"
}

requests库

发送请求

1
r = requests.get(url, headers=headers)

bs4库

解析浏览器响应

  • rrequests的响应结果
1
soup = bs4.BeautifulSoup(r.text, features='html.parser')

从soup对象获取内容

  • .select()中的内容,可以使用chrome浏览器获取
1
soup.select(f'#wp_news_w6 > ul > li.news.n{t+1}.clearfix > span.news_title > a')[0]['title'] 

词云图 jieba&wordcloud

安装

1
2
pip install jieba
pip install wordcloud

中文字体

绘图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import jieba
import wordcloud

# 读取文本
with open("read.txt",encoding="utf-8") as f:
paragragh = f.read()
# 将段落文本分词
ls = jieba.lcut(paragragh)
# 连接成字符串
text = ' '.join(ls)
# 停用词表
'''
可以从网上找停用词表,也可以自己定义
也可以在默认词表追加,方法如下:
from wordcloud import STOPWORDS
stopwords = STOPWORDS
stopwords.add('xxx') # 集合, 需要使用add()或update()方法
'''
stopwords = set()
content = []
stopwords.update(content)

# 创建wordcloud对象
wc = wordcloud.WordCloud(
font_path='SimHei.ttf',
width = 1000,
height = 1000,
background_color='white',
max_words=100,
stopwords=stopwords
)
# 生成词云
wc.generate(text)
# 保存图片
wc.to_file("write.png")

可执行脚本

自动调用解释器执行

1
#!/usr/bin/python3

中文编码

1
# coding=utf-8