自然語言處理中的詞袋模型
阿新 • • 發佈:2018-12-30
詞袋模型
from sklearn.feature_extraction.text import CountVectorizer
import os
import re
import jieba.posseg as pseg
# 載入停用詞表
stop_words_path = './stop_words/'
stopwords1 = [line.rstrip() for line in open(os.path.join(stop_words_path, '中文停用詞庫.txt'), 'r',encoding='utf-8')]
stopwords2 = [line.rstrip() for line in open(os.path.join(stop_words_path, '哈工大停用詞表.txt'), 'r',encoding='utf-8')]
stopwords3 = [line.rstrip() for line in
open(os.path.join(stop_words_path, '四川大學機器智慧實驗室停用詞庫.txt'), 'r', encoding='utf-8')]
stopwords = stopwords1 + stopwords2 + stopwords3
def proc_text(raw_line):
"""
處理文字資料
返回分詞結果
"""
# 1. 使用正則表示式去除非中文字元
filter_pattern = re.compile('[^\u4E00-\u9FD5]+')
chinese_only = filter_pattern.sub('', raw_line)
# 2. 結巴分詞+詞性標註
word_list = pseg.cut(chinese_only)
# 3. 去除停用詞,保留有意義的詞性
# 動詞,形容詞,副詞
used_flags = ['v', 'a', 'ad']
meaninful_words = []
for word, flag in word_list:
if (word not in stopwords) and (flag in used_flags):
meaninful_words.append(word)
return ' '.join(meaninful_words)
count_vectorizer = CountVectorizer()
print(count_vectorizer)
ch_text1 = ' 非常失望,劇本完全敷衍了事,主線劇情沒突破大家可以理解,可所有的人物都缺乏動機,正邪之間、婦聯內部都沒什麼火花。團結-分裂-團結的三段式雖然老套但其實也可以利用積攢下來的形象魅力搞出意思,但劇本寫得非常膚淺、平面。場面上排程混亂呆板,滿屏的鐵甲審美疲勞。只有笑點算得上差強人意。'
ch_text2 = ' 2015年度最失望作品。以為面面俱到,實則畫蛇添足;以為主題深刻,實則老調重彈;以為推陳出新,實則俗不可耐;以為場面很high,實則high勁不足。氣!上一集的趣味全無,這集的笑點明顯刻意到心虛。全片沒有任何片段給我有緊張激動的時候,太弱了,跟奧創一樣。'
ch_text3 = ' 《鐵人2》中勾引鋼鐵俠,《婦聯1》中勾引鷹眼,《美隊2》中勾引美國隊長,在《婦聯2》中終於……跟綠巨人表白了,黑寡婦用實際行動告訴了我們什麼叫忠貞不二;而且為了治療不孕不育連作戰武器都變成了兩支驗孕棒(堅決相信快銀沒有死,後面還得回來)'
ch_text4 = ' 雖然從頭打到尾,但是真的很無聊啊。'
ch_text5 = ' 劇情不如第一集好玩了,全靠密集笑點在提神。僧多粥少的直接後果就是每部寡姐都要換著隊友談戀愛,這特麼比打鬥還辛苦啊,真心求放過~~~(結尾彩蛋還以為是洛基呢,結果我呸!)'
ch_texts = [ch_text1, ch_text2, ch_text3, ch_text4, ch_text5]
corpus = [proc_text(ch_text) for ch_text in ch_texts]
print(corpus)
X = count_vectorizer.fit_transform(corpus)
print(X)
print(X.toarray())
new_text = '劇情混亂,太失望了'
new_pro_text = proc_text(new_text)
print(new_pro_text)
print(count_vectorizer.transform([new_pro_text]).toarray())