利用python實現簡單詞頻統計、構建詞雲


1、利用jieba分詞,排除停用詞stopword之后,對文章中的詞進行詞頻統計,並用matplotlib進行直方圖展示

# coding: utf-8
import codecs
import matplotlib.pyplot as plt
import jieba
# import sys
# reload(sys)
# sys.setdefaultencoding('utf-8')
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['FangSong']  # 指定默認字體
mpl.rcParams['axes.unicode_minus'] = False  # 解決保存圖像是負號'-'顯示為方塊的問題
plt.rcParams['font.sans-serif'] = ['SimHei']

stopword=[u'',u',',u'',u'(',u')',u'"',u':',u';',u'',u',',u'',u'',u'',u'',u'',u'',u'',u'']
word = []
counter = {}

with codecs.open('data.txt') as fr:
    for line in fr:
        line = line.strip()
        #print type(line)
        if len(line) == 0:
            continue
        line = jieba.cut(line, cut_all = False)
        for w in line:#.decode('utf-8'):
            if ( w in stopword) or len(w)==1: continue
            if not w in word :
                word.append(w)
            if not w in counter:
                counter[w] = 0
            else:
                counter[w] += 1

counter_list = sorted(counter.items(), key=lambda x: x[1], reverse=True)

print(counter_list[:50])
#for i,j in counter_list[:50]:print i

label = list(map(lambda x: x[0], counter_list[:10]))
value = list(map(lambda y: y[1], counter_list[:10]))

plt.bar(range(len(value)), value, tick_label=label)
plt.show()

注意:matplotlib展示中文需要進行相應設置

2、利用jieba分詞,利用collections統計詞頻,利用wordcloud生成詞雲,並定義了 詞頻背景,最后通過matplotlib展示,同樣需要設置字體

# coding: utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
# 導入擴展庫
import re # 正則表達式庫
import collections # 詞頻統計庫
import numpy as np # numpy數據處理庫
import jieba # 結巴分詞
import wordcloud # 詞雲展示庫
from PIL import Image # 圖像處理庫
import matplotlib.pyplot as plt # 圖像展示庫

# 讀取文件
fn = open('data.txt') # 打開文件
string_data = fn.read() # 讀出整個文件
fn.close() # 關閉文件

# 文本預處理
pattern = re.compile(u'\t|\n|\.|-|:|;|\)|\(|\?|"') # 定義正則表達式匹配模式
string_data = re.sub(pattern, '', string_data) # 將符合模式的字符去除

# 文本分詞
seg_list_exact = jieba.cut(string_data, cut_all = False) # 精確模式分詞
object_list = []
remove_words = [u'', u'', u'', u'',u'', u'',u'自己',u'', u'隨着', u'對於', u'',u'',u'',u'',u'',u' ',u'',u'',u'',u'',
                u'通常',u'如果',u'我們',u'需要'] # 自定義去除詞庫

for word in seg_list_exact: # 循環讀出每個分詞
    if word not in remove_words: # 如果不在去除詞庫中
        object_list.append(word) # 分詞追加到列表

# 詞頻統計
word_counts = collections.Counter(object_list) # 對分詞做詞頻統計
word_counts_top10 = word_counts.most_common(10) # 獲取前10最高頻的詞
print (word_counts_top10) # 輸出檢查

# 詞頻展示
img = Image.open('2018.png') #打開圖片
img_array = np.array(img) #將圖片裝換為數組
#mask = np.array(Image.open('wordcloud.jpg')) # 定義詞頻背景
wc = wordcloud.WordCloud(
    font_path='C:/Windows/Fonts/simhei.ttf', # 設置字體格式
    #font_path='/usr/share/fonts/truetype/arphic/ukai.ttc', #  設置字體格式
    background_color='white',
    mask=img_array,
    width=1000,
    height=800,
    # max_words=200, # 最多顯示詞數
    # max_font_size=100 # 字體最大值
)

wc.generate_from_frequencies(word_counts) # 從字典生成詞雲
image_colors = wordcloud.ImageColorGenerator(img_array) # 從背景圖建立顏色方案
wc.recolor(color_func=image_colors) # 將詞雲顏色設置為背景圖方案
plt.imshow(wc) # 顯示詞雲
plt.axis('off') # 關閉坐標軸
plt.show() # 顯示圖像


免責聲明!

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



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