文本數據分詞,詞頻統計,可視化 - Python


詞頻、分詞和可視化結合爬蟲,做一些作業。

  • 爬蟲庫requests
  • 詞頻統計庫collections
  • 數據處理庫numpy
  • 結巴分詞庫jieba
  • 可視化庫pyecharts等等。

數據的話直接從網上摳一些東西,這里摳一篇新聞。要導入的庫,一次性導入:

 1 import collections
 2 import re
 3 import jieba
 4 import requests
 5 import parsel
 6 from pyecharts.charts import Bar
 7 from pyecharts.globals import ThemeType
 8 import pyecharts.options as opts
 9 from stylecloud import stylecloud
10 from wordcloud import WordCloud
11 from PIL import Image
12 from matplotlib import pyplot as plt
13 import numpy as np

第一部分,提取網頁內容並寫入到文檔。

 1 def get_text():
 2     url = 'http://cpc.people.com.cn/n1/2022/0110/c164113-32327931.html'
 3     headers = {
 4         'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36',
 5     }
 6 
 7     response = requests.get(url=url, headers=headers)
 8     response.raise_for_status()
 9     response.encoding = response.apparent_encoding
10     print(response.text)
11     selector = parsel.Selector(response.text)
12     textResults = selector.xpath('//div[@class="show_text"]/p/text()').getall()
13     # 這種方式沒有獲取到粗體
14     with open('test.txt', mode='w+', encoding='utf-8') as f:
15         for item in textResults:
16             f.write(item + '\n') #

第二部分,詞頻統計,用collections,以便做統計詞頻的條形圖的時候使用。

 1 def words_counts():
 2     with open('test.txt', mode='r', encoding='utf-8') as f:
 3         strData = f.read()
 4 
 5     # 替換符合parrtern的文本
 6     pattern = re.compile(r'\t|,|/|。|\n|\.|-|:|;|\)|\(|\?|,。,!”"')
 7     strData = re.sub(pattern, '', strData)  # 將符合模式的字符去除
 8 
 9     # 開始分詞,精准模式
10     words = jieba.cut(strData, cut_all=False)
11     resultWords = [] # 空列表
12     # 自定義停用詞
13     stopWords = [u'', u'', u'', u'', u'', u'', u'', u'',
14                     '' u'隨着', u'對於', u'', u'', u'', u'', u'',
15                     u' ', u'', u'', u'', u'', u'通常', u'如果', u'',
16                     u'', u'', u'', u'', u'', u'', u'', u'',
17                     u'', u'', u'', u'', u'', u'', u'',
18                     u'什么', u'·', u'', u'沒有', u'', u'', u'']
19     #
20     for word in words:
21         if word not in stopWords:
22             resultWords.append(word)
23     # print(resultWords) #  打印結果
24 
25     # 開始統計詞頻
26     word_counts = collections.Counter(resultWords) # 一個詞頻統計對象
27     # print(word_counts)
28 
29     # 獲取高頻詞的列表
30     word_counts_all = word_counts.most_common() # 一個列表,列表里是元組
31     # print(word_counts_all)
32     word_counts_top10 = word_counts.most_common(10)
33     return word_counts_top10

第三部分,利用stylecloud和wordcloud制作詞。

首先是stylecloud:

 1 def gen_style_words():
 2     with open('test.txt', mode='r', encoding='utf-8') as f:
 3         word_list = jieba.cut(f.read())
 4         print(word_list)
 5         result_words = ' '.join(word_list)
 6         print(result_words)
 7     # 制作詞雲
 8     # 停用詞
 9     stopWords = [u'', u'', u'', u'', u'', u'', u'', u'',
10                  '' u'隨着', u'對於', u'', u'', u'', u'', u'',
11                  u' ', u'', u'', u'', u'', u'通常', u'如果', u'',
12                  u'', u'', u'', u'', u'', u'', u'', u'',
13                  u'', u'', u'', u'', u'', u'', u'',
14                  u'什么', u'·', u'', u'沒有', u'', u'', u'']
15     stylecloud.gen_stylecloud(
16         text=result_words,
17         size=1280,  # stylecloud的大小,長度和寬度,
18         font_path='C:\\Windows\\Fonts\\simhei.ttf',  # 字體路徑
19         max_words=150,  # stylecloud中能容的最多詞數
20         max_font_size=200,  # 最大字號
21         # invert_mask=, # 蒙版
22         custom_stopwords=stopWords,  # 停用詞
23         output_name='1.png',  # 輸出的名字
24     )

結果展示:

其次是worldcloud:

 1 def word_cloud_style():
 2     """
 3     另外一種生成詞雲的方法
 4     """
 5     # f = open('../Spiders/content.txt', 'r', encoding='utf-8')  # 這是數據源,也是想生成詞雲的數據
 6     # txt = f.read()  # 讀取文件
 7     # print(type(txt))
 8     # print('=========================================')
 9     # f.close()  # 關閉文件,其實可以用withopen
10     with open('test.txt', mode='r', encoding='utf-8') as f:
11         txt = f.read()
12     # 如果是文章的話,需要用到jieba分詞,分完之后也可以自己處理下再生成詞雲
13     newTxt = re.sub("A-Z0-9-a-z\!\%\[\]\,\。", "", txt)
14     # print(newTxt)
15 
16     words = jieba.lcut(newTxt)
17     print(words)
18     img = Image.open(r'wc.jpg')  # 想要做的形狀
19     img_array = np.array(img)
20 
21     # 相關配置,里面這個collections可以避免重復
22     wordcloud = WordCloud(
23         background_color='white',
24         width=1080,
25         height=960,
26         # font_path = "../文悅新青年.otf",
27         font_path='C:/Windows/Fonts/simhei.ttf',
28         max_words=150,
29         scale=10,  # 清晰度
30         max_font_size=100,
31         mask=img_array,
32         collocations=False).generate(newTxt)
33 
34     plt.imshow(wordcloud)
35     plt.axis('off')
36     plt.show()
37     wordcloud.to_file('wc.png')

結果展示:

 

第四部分,詞頻統計條形圖。

 1 def echart_top_10():
 2     data = words_counts()
 3     lab = [i[0] for i in data]
 4     num = [i[1] for i in data]
 5     # print(lab, num)
 6 
 7     bar = (
 8         Bar(init_opts=opts.InitOpts(width='1000px', height='700px', theme=ThemeType.LIGHT))
 9         .add_xaxis(xaxis_data=lab)
10         .add_yaxis(
11             series_name='',
12             y_axis=num,
13             label_opts=opts.LabelOpts(is_show=True, color='red'),
14             bar_max_width='100px',
15         )
16         .set_global_opts(
17             title_opts=opts.TitleOpts(
18                 title='高詞頻前10',
19                 title_textstyle_opts=opts.TextStyleOpts(font_size=28,)
20             ),
21             legend_opts=opts.LegendOpts(
22                 pos_top='10%',
23                 pos_left='10%',
24             ),
25             xaxis_opts=opts.AxisOpts(
26                 axislabel_opts=opts.LabelOpts(rotate=45), # 傾斜45度
27             ),
28             toolbox_opts=opts.ToolboxOpts(),
29             tooltip_opts=opts.TooltipOpts(
30                 is_show=True,
31                 trigger='axis',# 觸發類型,(axis表示坐標軸觸發,鼠標移動上去的時候會有一條垂直於x軸的實線跟隨鼠標移動,並且提示信息)
32                 axis_pointer_type='cross',# 指示器類型,(Cross表示生成兩條分別垂直於x軸和y軸的虛線,不啟用trigger才會顯示完全)
33             ),
34         )
35     ).render('top10.html')

詞頻統計條形圖,調用了工具欄,可以通過右上角的工具欄切換為線圖。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM