NLTK安裝使用全過程--python


前言

之前做實驗用到了情感分析,就下載了一下,這篇博客記錄使用過程。

下載安裝到實戰詳細步驟

NLTK下載安裝

先使用pip install nltk 安裝包
然后運行下面兩行代碼會彈出如圖得GUI界面,注意下載位置,然后點擊下載全部下載了大概3.5G。

import nltk
nltk.download()!

image

下載成功后查看是否可以使用,運行下面代碼看看是否可以調用brown中的詞庫

from nltk.corpus import brown

print(brown.categories())  # 輸出brown語料庫的類別
print(len(brown.sents()))  # 輸出brown語料庫的句子數量
print(len(brown.words()))  # 輸出brown語料庫的詞數量

'''
結果為:
['adventure', 'belles_lettres', 'editorial', 'fiction', 'government', 'hobbies', 
'humor', 'learned', 'lore', 'mystery', 'news', 'religion', 'reviews', 'romance', 
'science_fiction']
57340
1161192
'''

這時候有可能報錯,說在下面文件夾中沒有找到nltk_data
把下載好的文件解壓在復制到其中一個文件夾位置即可,注意文件名,讓后就能正常使用!

image

實戰:運用自己的數據進行操作

一、使用自己的訓練集訓練和分析

可以看到我的訓練集和代碼的結構是這樣的:imagepos和neg里面是txt文本
鏈接:https://pan.baidu.com/s/1GrNg3ziWJGhcQIWBCr2PMg
提取碼:1fb8

import nltk.classify.util
from nltk.classify import NaiveBayesClassifier
import os
from nltk.corpus import stopwords
import pandas as pd


def extract_features(word_list):
    return dict([(word, True) for word in word_list])

#停用詞
stop = stopwords.words('english')
stop1 = ['!', ',' ,'.' ,'?' ,'-s' ,'-ly' ,' ', 's','...']
stop = stop1+stop
print(stop)

#讀取txt文本
def readtxt(f,path):
    data1 = ['microwave']
    # 以 utf-8 的編碼格式打開指定文件
    f = open(path+f, encoding="utf-8")
    # 輸出讀取到的數據
    #data = f.read().split()
    data = f.read().split()
    for i in range(len(data)):
        if data[i] not in stop:
            data[i] = [data[i]]
            data1 = data1+data[i]
    # 關閉文件
    f.close()
    del data1[0]
    return data1


if __name__ == '__main__':

    # 加載積極與消極評論  這些評論去掉了一些停用詞,是在readtxt韓碩里處理的,
    #停用詞如 i am you a this 等等在評論中是非常常見的,有可能對結果有影響,應該事先去除
    positive_fileids = os.listdir('pos')  # 積極 list類型 42條數據 每一條是一個txt文件
    print(type(positive_fileids), len(positive_fileids)) # list類型 42條數據 每一條是一個txt文件
    negative_fileids = os.listdir('neg')#消極 list類型 22條數據 每一條是一個txt文件自己找的一些數據
    print(type(negative_fileids),len(negative_fileids))

    # 將這些評論數據分成積極評論和消極評論
    # movie_reviews.words(fileids=[f])表示每一個txt文本里面的內容,結果是單詞的列表:['films', 'adapted', 'from', 'comic', 'books', 'have', ...]
    # features_positive 結果為一個list
    # 結果形如:[({'shakesp: True, 'limit': True, 'mouth': True, ..., 'such': True, 'prophetic': True}, 'Positive'), ..., ({...}, 'Positive'), ...]
    path = 'pos/'
    features_positive = [(extract_features(readtxt(f,path=path)), 'Positive') for f in positive_fileids]
    path = 'neg/'
    features_negative = [(extract_features(readtxt(f,path=path)), 'Negative') for f in negative_fileids]

    # 分成訓練數據集(80%)和測試數據集(20%)
    threshold_factor = 0.8
    threshold_positive = int(threshold_factor * len(features_positive))  # 800
    threshold_negative = int(threshold_factor * len(features_negative))  # 800
    # 提取特征 800個積極文本800個消極文本構成訓練集  200+200構成測試文本
    features_train = features_positive[:threshold_positive] + features_negative[:threshold_negative]
    features_test = features_positive[threshold_positive:] + features_negative[threshold_negative:]
    print("\n訓練數據點的數量:", len(features_train))
    print("測試數據點的數量:", len(features_test))

    # 訓練朴素貝葉斯分類器
    classifier = NaiveBayesClassifier.train(features_train)
    print("\n分類器的准確性:", nltk.classify.util.accuracy(classifier, features_test))
    print("\n五大信息最豐富的單詞:")
    for item in classifier.most_informative_features()[:5]:
        print(item[0])

    # 輸入一些簡單的評論
    input_reviews = [
        "works well with proper preparation.",
        ]

    #運行分類器,獲得預測結果
    print("\n預測:")
    for review in input_reviews:
        print("\n評論:", review)
        probdist = classifier.prob_classify(extract_features(review.split()))
        pred_sentiment = probdist.max()
        # 打印輸出
        print("預測情緒:", pred_sentiment)
        print("可能性:", round(probdist.prob(pred_sentiment), 2))

print("結束")

運行結果:這里的准確性有點高,這是因為我選取的一些數據是非常明顯的表達積極和消極的所以處理結果比較難以相信

<class 'list'> 42
<class 'list'> 22

訓練數據點的數量: 50
測試數據點的數量: 14

分類器的准確性: 1.0

五大信息最豐富的單詞:
microwave
product
works
ever
service

預測:

評論: works well with proper preparation.
預測情緒: Positive
可能性: 0.77
結束

二、使用自帶庫分析

import pandas as pd

from nltk.sentiment.vader import SentimentIntensityAnalyzer
# 分析句子的情感:情感分析是NLP最受歡迎的應用之一。情感分析是指確定一段給定的文本是積極還是消極的過程。
# 有一些場景中,我們還會將“中性“作為第三個選項。情感分析常用於發現人們對於一個特定主題的看法。
# 定義一個用於提取特征的函數
# 輸入一段文本返回形如:{'It': True, 'movie': True, 'amazing': True, 'is': True, 'an': True}
# 返回類型是一個dict

if __name__ == '__main__':

    # 輸入一些簡單的評論
    #data = pd.read_excel('data3/microwave1.xlsx')
    name = 'hair_dryer1'
    data = pd.read_excel('../data3/'+name+'.xlsx')
    input_reviews = data[u'review_body']
    input_reviews = input_reviews.tolist()
    input_reviews = [
        "works well with proper preparation.",
        "i hate that opening the door moves the microwave towards you and out of its place. thats my only complaint.",
        "piece of junk. got two years of use and it died. customer service says too bad. whirlpool dishwasher died a few months ago. whirlpool is dead to me.",
        "am very happy with  this"
        ]

    #運行分類器,獲得預測結果
    for sentence in input_reviews:
        sid = SentimentIntensityAnalyzer()
        ss = sid.polarity_scores(sentence)
        print("句子:"+sentence)
        for k in sorted(ss):
            print('{0}: {1}, '.format(k, ss[k]), end='')

        print()
print("結束")

結果:

句子:works well with proper preparation.
compound: 0.2732, neg: 0.0, neu: 0.656, pos: 0.344, 
句子:i hate that opening the door moves the microwave towards you and out of its place. thats my only complaint.
compound: -0.7096, neg: 0.258, neu: 0.742, pos: 0.0, 
句子:piece of junk. got two years of use and it died. customer service says too bad. whirlpool dishwasher died a few months ago. whirlpool is dead to me.
compound: -0.9432, neg: 0.395, neu: 0.605, pos: 0.0, 
句子:am very happy with  this
compound: 0.6115, neg: 0.0, neu: 0.5, pos: 0.5, 
結束

結果解釋:
compound就相當於一個綜合評價,主要和消極和積極的可能性有關
neg:消極可能性
pos:積極可能性
neu:中性可能性


免責聲明!

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



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