# encoding:utf-8
# 导入库-------------------------------
import requests
import pandas as pd
import math
import re
import jieba
from collections import Counter
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import random
import matplotlib
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['axes.unicode_minus'] = False
import sklearn
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
import matplotlib.pyplot as plt
import matplotlib
from sklearn.feature_extraction.text import TfidfVectorizer
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['axes.unicode_minus'] = False
import random
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
from collections import Counter
from pyecharts.charts import * # 图表
from pyecharts.components import Table # 表格
from pyecharts import options as opts # 配置
from pyecharts.commons.utils import JsCode
import random # 随机数
import datetime #时间
from pyecharts.charts import Pie
from pyecharts.charts import Page
def bing_tu(label_list, size, title_name, figsize_x):
""""
# 饼图
label_list = ["第一部分", "第二部分", "第三部分"]
size = [55, 35, 10] # 各部分大小
"""
def make_autopct(values):
def my_autopct(pct):
total = sum(values)
val = int(round(pct * total / 100.0))
# 同时显示数值和占比的饼图
return '{p:.2f}% ({v:d})'.format(p=pct, v=val)
return my_autopct
color = []
colors = ["red", "green", "blue", "yellow"] # 各部分颜色
while len(color) < len(label_list):
color.append(colors[random.randint(0, 3)])
# explode = [0.05, 0, 0] # 各部分突出值
fig = plt.figure(figsize=(figsize_x, figsize_x))
plt.subplot(131)
plt.title(title_name)
plt.pie(size, labels=label_list, labeldistance=1.2, autopct=make_autopct(size))
# plt.savefig("barChart.jpg")
plt.show()
def zhu_zhuang_tu(label_list, size, title_name, y_name, x_name):
"""
# 柱状图
label_list = ["第一部分", "第二部分", "第三部分"]
size = [55, 35, 10] # 各部分大小
"""
fig = plt.figure()
plt.bar(label_list, size, 0.5, color="green")
plt.xlabel(x_name)
plt.ylabel(y_name)
plt.title(title_name)
# plt.savefig("barChart.jpg")
plt.show()
def tiaoxing_zhuzhangtu(labels, values):
"""
# 横向的柱状图
# labels=['体育和娱乐业', '批发和零售业', '租赁和商务服务业', '建筑业']
# values=[251, 316, 52, 45]
"""
plt.barh(labels, values) # 以时间为纵轴,收盘价为高度绘制横向条形图
plt.show()
def quxiantu(x, y):
"""
# 曲线图
y=[1,5,2,6,8,9]
x=[1,2,3,4,5,6]
"""
plt.xlabel('日期', fontsize=8)
plt.ylabel('价格', fontsize=8)
# plt.plot(x_low,datasz_low,label='最高价',color="r")
plt.plot(x, y, label='最低价', color="y")
plt.title("上证指数最高价和最低价曲线图")
plt.show()
return 0
def pyecharts_bingtu(x,y):
"""
x = ["直接访问", "邮件营销", "联盟广告", "视频广告", "搜索引擎"]
y = [335, 310, 274, 235, 400] 要求必须是整数
"""
c = (
Pie()
.add("", [list(z) for z in zip(x, y)]) # zip函数两个部分组合在一起list(zip(x,y))-----> [(x,y)]
.set_global_opts(title_opts=opts.TitleOpts(title="2022年1月天津市流流出口分析柱状图", pos_left="center")) # 标题
.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}")) # 数据标签设置
)
c.render_notebook()
c.render(path=r"pyecharts_bingtu_饼图_bar.html")
def pyecharts_zhuzhuangtu(x, y):
"""
x = ["直接访问", "邮件营销", "联盟广告", "视频广告", "搜索引擎"]
y = [335, 310, 274, 235, 400] 要求必须是整数
"""
bar = Bar() # 初始化图表
bar.add_xaxis(x) # x轴
bar.add_yaxis('数目', y) # y轴
bar.set_global_opts(title_opts=opts.TitleOpts(title="天津市流入人口分析柱状图"))
bar.render(path=r"pyecharts_zhuzhuangtu_柱状图_bar.html")
def plt_picture_ciyun(n):
"""
词云
传入的n是:我 老婆 走 了 四年 总会 不经意 想起 那 感觉 没 经历 的 很 难 体会
"""
wc = WordCloud(
# 设置字体,不指定就会出现乱码
font_path='simhei.ttf',
# 设置背景色
background_color='white',
# 设置背景宽
width=500,
# 设置背景高
height=350,
# 最大字体
max_font_size=50,
# 最小字体
min_font_size=10,
mode='RGBA'
# colormap='pink'
)
# 产生词云
wc.generate(n)
# 显示图片
# 指定所绘图名称
plt.figure("jay")
# 以图片的形式显示词云
plt.imshow(wc)
# 关闭图像坐标系
plt.axis("off")
# 保存词云图片
# plt.savefig("2209070221.png")
plt.show()
def re_pipei_word(text):
"""
正则提取文本的汉字
text = "也像疼111WWW%% __"
"""
res = re.findall('[\u4e00-\u9fa5]', str(text))
# print(res) #['也', '像', '疼']
# print("".join(res)) 也像疼
return "".join(res)
def jieba_cut_word(text):
"""
jieba分词
text=滴滴代驾不靠谱,在司机端总是接不到单子
"""
res1 = jieba.lcut("滴滴代驾不靠谱,在司机端总是接不到单子。", cut_all=False) # 不存在多余词
# ['滴滴', '代驾', '不靠', '谱', ',', '在', '司机', '端', '总是', '接', '不到', '单子', '。']
res2 = jieba.lcut("今天空车返回,在路上遇到行政执法,平台不派单。", cut_all=True) # 有多余词
# ['今天', '天空', '空车', '返回', ',', '在', '路上', '遇到', '行政', '执法', ',', '平台', '不', '派', '单', '。']
return res1
def dict_sort(dic):
"""
字典排序
"""
count = sorted(dic.items(), key=lambda x: x[1], reverse=True) # True 是降序 False是升序
return count
def tfidf_word(corpus):
"""
tfodf 提取关键词:
import sklearn
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
corpus = ['TF-IDF 主要 思想 是', '算法 一个 重要 特点 可以 脱离 语料库 背景',
'如果 一个 网页 被 很多 其他 网页 链接 说明 网页 重要',
'原始 文本 进行 标记',
'主要 思想']
"""
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(corpus)
data = {'word': vectorizer.get_feature_names_out(),
'tfidf': X.toarray().sum(axis=0).tolist()}
df = pd.DataFrame(data)
df = df.sort_values(by='tfidf', ascending=True) # True是从小达到 False是从大到小
res = {}
for i in df.values:
res[i[0]] = i[1]
# print(res){'链接': 0.2556396904397093, '说明': 0.2556396904397093...}
return res
def tongci_count(data):
"""
from collections import Counter
列表统计
data是一个列表
"""
res = dict(Counter(data))
return res