먼저 관련 데이터를 크롤링하고 데이터를 다른 파일에 저장하여 후속 데이터 처리를 용이하게해야합니다.
import time import json import requests from datetime import datetime import pandas as pd import numpy as np def catch_data () : url = 'https : //view.inews.qq.com/g2/getOnsInfo ? name = disease_h5'response = requests. get (url = url) .json () #return data dictionary data = json.loads (reponse [ 'data']) return data data = catch_data () data.keys () lastUpdateTime = data [ 'lastUpdateTime'] # 데이터 세부 사항 , 데이터 구조는 더 복잡합니다. 단계별로 인쇄하고 먼저 데이터 구조를 이해합니다. areaTree = data [ 'areaTree'] # domestic data china_data = areaTree [0] [ 'children'] china_list = [] for a in range ( len (중국 _ 데이터))) : = china_data [a] [ '이름'] province_list = china_data [a] [ 'children'] for b in range (len (province_list)) : city = province_list [b] [ 'name'] total = province_list [b] [ 'total'] today = province_list [b] [ 'today'] china_dict = {} china_dict [ 'province'] = 지방 china_dict [ 'city'] = city china_dict [ 'total'] = total china_dict [ 'today'] = 오늘 china_list.append (china_dict) china_data = pd .DataFrame (china_list) china_data.head () # 定义 数据 处理 函数 def confirm (x) : confirm = eval (str (x)) [ 'confirm'] return confirm def dead (x) : dead = eval (str (x)) [ 'dead'] return dead def heal (x) : heal = eval (str (x)) [ 'heal'] return heal # 函数 映射 china_data [ 'confirm'] = china_data [ 'total']. map (confirm) china_data [ 'dead' ] = china_data [ 'total']. map (dead) china_data [ 'heal'] = china_data [ 'total']. map (heal) china_data = china_data [[ "province", "city", "confirm", "dead ","heal "]] china_data.head () area_data = china_data.groupby ("province ") ["confirm "]. sum (). reset_index () area_data.column = ["province ","confirm "] # print (area_data) area_data.to_csv ( "confirm.csv", encoding = "utf_8_sig") area_data = china_data.groupby ( "province") [ "dead"]. sum (). reset_index () area_data.column = [ "province", "dead"] # print (area_data) area_data.to_csv ( "dead.csv", encoding = "utf_8_sig") area_data = china_data.groupby ( "province") [ "heal"]. sum (). reset_index () area_data.column = [ "province", "heal "] # print (area_data) area_data.to_csv ("heal.csv ", encoding ="utf_8_sig ")
소문이있는 데이터가 있습니다
가져 오기 요청 가져 오기 팬더를 pd 클래스 SpiderRumor (object) : def __init __ (self) : self.url = "https://vp.fact.qq.com/loadmore?artnum=0&page=%s"self.header = { " User-Agent ":"Mozilla / 5.0 (iPhone, Mac OS X와 같은 CPU iPhone OS 11_0) AppleWebKit / 604.1.38 (Gecko와 같은 KHTML) 버전 /11.0 Mobile / 15A372 Safari / 604.1 ", } def spider_run (self) : df_all = list () for url in [self.url % i for i in range (61)] : data_list = requests.get (url, headers = self.header) .json () [ "content"] temp_data = [[ df [ "title"], df [ "date"], df [ "result"], df [ "explain"], df [ "tag"]] data_list의 df] df_all.extend (temp_data) print (임시 데이터 [0]) pd.DataFrame (df_all, columns = [ "title", "date", "result", "explain", "tag"]). to_csv ( "冠状 病毒 谣言 数据 .csv", encoding = "utf_8_sig") if __name__ == '__main__': spider = SpiderRumor () spider.spider_run ()
모든 데이터를 얻은 후에 데이터 시각화를 완료합시다!
먼저 matplotlib 라이브러리로 만든 시각화를 살펴보십시오.
라인 차트 :
import numpy as np import pandas as pd import matplotlib.pyplot as plt # Windows 시스템 설정 중국어 글꼴 plt.rcParams [ 'font.sans-serif'] = [ 'SimHei'] plt.rcParams [ 'axes.unicode_minus'] = False data = pd.read_csv ( 'Coronavirus rumors data.csv') labels = data [ 'date']. value_counts (). index.tolist () sizes = data [ 'date']. value_counts (). values.tolist () plt.figure (figsize = (30, 8)) plt.plot (labels, sizes) plt.xticks (labels, labels, rotation = 45) plt.title ( '일일 루머 수', fontsize = 40) plt. show ()
효과 사진 :
히스토그램 :
import numpy as np import pandas as pd import matplotlib.pyplot as plt # Windows 시스템 설정 중국어 글꼴 plt.rcParams [ 'font.sans-serif'] = [ 'SimHei'] plt.rcParams [ 'axes.unicode_minus'] = False data = pd.read_csv ( "코로나 바이러스 소문 data.csv ") df = pd.Series ([j for i in [eval (i) for i in data [ "tag"]. tolist ()] for j in i]) .value_counts () [: 20] X = df.index.tolist () Y = df.values.tolist () plt.figure (figsize = (15, 8)) # 캔버스 설정 plt.bar (X, Y, color = "blue") plt.tight_layout () plt.grid (ls = '-.') plt.show ()
효과 사진 :
파이 차트:
import numpy as np import pandas as pd import matplotlib.pyplot as plt # Windows 시스템 설정 중국어 글꼴 plt.rcParams [ 'font.sans-serif'] = [ 'SimHei'] plt.rcParams [ 'axes.unicode_minus'] = False data = pd.read_csv ( "coronavirus rumors data.csv") labels = data [ "explain"]. value_counts (). index.tolist () # 각 텍스트 크기 = data [ "explain"]. value_counts ( ) .values.tolist () # 각 텍스트 색상에 해당하는 발생 횟수를 필터링하는 것으로 이해할 수 있습니다. = [ 'lightgreen', 'gold', 'lightskyblue', 'lightcoral'] plt.figure (figsize = (18, 10)) plt.pie (크기, 레이블 = 레이블, 색상 = 없음, autopct = '% 1.1f %%', shadow = True, explode = (0.1, 0.1, 0, 0, 0, 0, 0, 0, 0, 0), textprops = { 'fontsize': 15, 'color': 'black'}) # shadow = True는 그림자를 의미합니다. plt.axis ( 'equal') # 양의 원으로 설정 equal ') # 양의 원으로 설정 plt.legend (loc ='upper right ', ncol = 2) plt.show ()
효과 사진 :
그런 다음 pyecharts 라이브러리의 시각화
라인 차트 :
pd로 팬더 가져 오기 pyecharts에서 np 로 numpy 가져 오기 import Line data = pd.read_csv ( "dead.csv") x = data [ "province"] y = data [ "dead"] line = Line ( '국내 사망 선 차트' ) line.add ( '확인 번호', x, y, is_label_show = True) line.render ( 'Domestic death line chart.html ') line.render_notebook ()
pandas를 pd로 import numpy를 np 로 pyecharts에서 import Line data = pd.read_csv ( "heal.csv") x = data [ "province"] y = data [ "heal"] line = Line ( 'Domestic healing line chart' ) line.add ( '확인 번호', x, y, is_label_show = True) line.render ( '국내 치료 라인 차트 .html ') line.render_notebook ()
from pyecharts import Line import numpy as np import pandas as pd data = pd.read_csv ( "dead.csv") x = data [ "province"] y = data [ "dead"] data1 = pd.read_csv ( "heal.csv ") z = data1 ["heal "] line = Line ("治愈 死亡 折线 图 ") line.add ("治愈 ", x, z, mark_point = ["max ","min "], mark_line = ["average "]) line.add ("死亡 ", x, y, mark_point = ["max ","min "], mark_line = ["average "]) line.render ("治愈 死亡 折线 图 .html ")
import pandas as pd import numpy as np from pyecharts import Line data = pd.read_csv ( "confirm.csv") x = data [ "province"] y = data [ "confirm"] line = Line ( '국내 확인 된 선 차트' ) line.add ( '확인 번호', x, y, is_label_show = True) line.render ( '국내 확인 라인 차트 .html ') line.render_notebook ()
히스토그램 :
from pyecharts import Bar import numpy as np import pandas as pd data = pd.read_csv ( "dead.csv") x = data [ "province"] y = data [ "dead"] data1 = pd.read_csv ( "heal.csv ") z = data1 ["heal "] bar = Bar ("治愈 死亡 柱状图 ") bar.add ("治愈 ", x, z, is_stack = True, is_label_show = True) bar.add ("死亡 ", x , y, is_stack = True, is_label_show = True) bar.render ( "治愈 死亡 柱状图 .html")
링 다이어그램 :
from pyecharts import Pie import pandas as pd import numpy as np data = pd.read_csv ( "dead.csv") x = data [ "province"] y = data [ "dead"] pie = Pie ( "死亡 环 图", title_pos = 'right') pie.add ( "", x, y, radius = [40, 75], label_text_color = None, is_label_show = True, is_more_utils = True, legend_orient = "vertical", legend_pos = "left", ) pie.render (path = "死亡 环 图 .html")
from pyecharts import Pie import pandas as pd import numpy as np data = pd.read_csv ( "heal.csv") x = data [ "province"] y = data [ "heal"] pie = Pie ( "治愈 环 图", title_pos = 'right') pie.add ( "", x, y, radius = [40, 75], label_text_color = None, is_label_show = True, is_more_utils = True, legend_orient = "vertical", legend_pos = "left", ) pie.render (path = "治愈 环 图 .html")
from pyecharts import Pie import pandas as pd import numpy as np data = pd.read_csv ( "confirm.csv") x = data [ "province"] y = data [ "confirm"] pie = Pie ( "确诊 环 图", title_pos = 'right') pie.add ( "", x, y, radius = [40, 75], label_text_color = None, is_label_show = True, is_more_utils = True, legend_orient = "vertical", legend_pos = "left", ) pie.render (path = "确诊 环 图 .html")
from pyecharts import Pie import numpy as np import pandas as pd data = pd.read_csv ( "冠状 病毒 谣言 数据 .csv") df = pd.Series ([j for i in [eval (i) for i in data [ "tag "] .tolist ()] for j in i]). value_counts () [: 20] X = df.index.tolist () Y = df.values.tolist () pie = Pie ("谣言 关键字 环 图 " , title_pos = 'center') pie.add ( "", X, Y, radius = [40, 75], label_text_color = None, is_label_show = True, is_more_utils = True, legend_orient = "vertical", legend_pos = "left", ) pie.render (path = "谣言 环 图 .html")
단어 구름 :
pyecharts에서 pd 로 팬더 가져 오기 import WordCloud import matplotlib.pyplot as plt # Windows 시스템 설정 중국어 글꼴 plt.rcParams [ 'font.sans-serif'] = [ 'SimHei'] plt.rcParams [ 'axes.unicode_minus'] = False data = pd.read_csv ( "confirm.csv") x = data [ "province"] y = data [ "confirm"] wordcloud = WordCloud (width = 900, height = 420) wordcloud.add ( "", x, y , word_size_range = [20, 100]) wordcloud.render ( "Epidemic Word Cloud Diagram.html ") wordcloud.render_notebook ()
import numpy as np import pandas as pd from pyecharts import WordCloud import matplotlib.pyplot as plt # Windows 시스템 설정 중국어 글꼴 plt.rcParams [ 'font.sans-serif'] = [ 'SimHei'] plt.rcParams [ 'axes.unicode_minus '] = False data = pd.read_csv ( "coronavirus rumors data.csv ") df = pd.Series ([j for i in [eval (i) for i in data [ "tag"]. tolist ()] for j i]). value_counts () [: 20] X = df.index.tolist () Y = df.values.tolist () wordcloud = WordCloud (width = 1300, height = 620) wordcloud.add ( "", X , Y, word_size_range = [20, 100]) wordcloud.render ( "rumor word cloud diagram.html ") wordcloud.render_notebook ()
마지막으로 일괄 실행 프로그램을위한 작은 스크립트가 첨부됩니다.
glob에서 os 가져 오기 import glob # os.system ( '谣言 饼图 .py') ls = glob ( '*. py') # print (len (ls)) for i in ls : if i == '运行 .py ': 계속 print (i) os.system (i)
파이썬을 함께 배우고, Xiaobai의지도, 공유를 가르치고, 나에게 개인 메시지를 보내는 것을 기억하십시오
최근 많은 친구들이 비공개 메시지를 통해 파이썬 학습 문제에 대해 상담했습니다. 의사 소통을 용이하게하려면 파란색을 클릭하여 토론 에 참여하고 리소스베이스에 직접 답변 하십시오.