1. 程式人生 > >大作業之中文文字分類(終稿)

大作業之中文文字分類(終稿)

import os
import numpy as np
import sys
from datetime import datetime
import gc

path = 'H:\大三上大作業\python大作業\date'
import jieba
with open(r'H:\大三上大作業\python大作業\stopsCN.txt', encoding='utf-8') as f:
    stopwords = f.read().split('\n')
#print(stopwords.shape)#檢視停用的字元數量
# for w in stopwords:#檢視stopwords檔案資料
#     print(w)

#文字預處理
def processing(tokens):
    tokens = "".join([char for char in tokens if char.isalpha()])# 去掉非字母漢字的字元
    tokens = [token for token in jieba.cut(tokens, cut_all=True) if len(token) >= 2]#分詞
    tokens = " ".join([token for token in tokens if token not in stopwords])# 去掉停用詞
    return tokens

tokenList = []
targetList = []
for root, dirs, files in os.walk(path):
    # print(root)#地址
    # print(dirs)#子目錄
    # print(files)#詳細檔名
    for f in files:
        filePath = os.path.join(root, f)#地址拼接
        with open(filePath, encoding='utf-8') as f:
            content = f.read()
            target = filePath.split('\\')[-2]
            targetList.append(target)
            tokenList.append(processing(content))


#建模
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB, MultinomialNB
from sklearn.model_selection import cross_val_score
from sklearn.metrics import classification_report

x_train, x_test, y_train, y_test = train_test_split(tokenList, targetList, test_size=0.3, stratify=targetList)
vectorizer = TfidfVectorizer()
X_train = vectorizer.fit_transform(x_train)
X_test = vectorizer.transform(x_test)
from sklearn.naive_bayes import MultinomialNB

mnb = MultinomialNB()
module = mnb.fit(X_train, y_train)
y_predict = module.predict(X_test)
scores = cross_val_score(mnb, X_test, y_test, cv=5)
print("驗證結果:%.3f" % scores.mean())
print("分類結果:\n", classification_report(y_predict, y_test))

import collections
# 測試集和預測集的各類新聞數量
testCount = collections.Counter(y_test)
predCount = collections.Counter(y_predict)
print('實際:', testCount, '\n', '預測', predCount)
# 建立標籤列表,實際結果與預測結果
nameList = list(testCount.keys())
testList = list(testCount.values())
predictList = list(predCount.values())
x = list(range(len(nameList)))
print("類別:", nameList, '\n', "實際:", testList, '\n', "預測:", predictList)

# 畫圖
import matplotlib.pyplot as plt
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['FangSong'] # 指定字型
plt.figure(figsize=(7,5))
total_width, n = 0.6, 2
width = total_width / n
plt.bar(x, testList, width=width,label='實際',fc = 'black')
for i in range(len(x)):
    x[i] = x[i] + width
plt.bar(x, predictList,width=width,label='預測',tick_label = nameList,fc='r')
plt.grid()
plt.title('實際和預測對比圖',fontsize=17)
plt.xlabel('新聞類別',fontsize=17)
plt.ylabel('頻數',fontsize=17)
plt.legend(fontsize =17)
plt.tick_params(labelsize=15)
plt.show()