Python 自然語(yǔ)言處理工具包(Natural Language Toolkit,簡(jiǎn)稱 NLTK)是一款 Python 的庫(kù),主要用于處理自然語(yǔ)言的相關(guān)問(wèn)題,如文本清洗、標(biāo)記化、分詞、語(yǔ)義分析、詞性標(biāo)注、文本分類等功能,是數(shù)據(jù)科學(xué)家和機(jī)器學(xué)習(xí)工程師不可或缺的工具之一。
本文將介紹學(xué)習(xí) Python NLTK 的路線,包括從簡(jiǎn)單的文本處理開(kāi)始,到掌握較為復(fù)雜的自然語(yǔ)言處理技術(shù),同時(shí)提供一些學(xué)習(xí)資料和優(yōu)秀實(shí)踐,幫助你快速入門 Python NLTK,提高自己的自然語(yǔ)言處理能力。
一、基礎(chǔ)知識(shí)
- Python 基礎(chǔ)
學(xué)習(xí) Python NLTK,首先需要掌握 Python 的基本語(yǔ)法和語(yǔ)言特性,并學(xué)會(huì)使用 Python 安裝和管理第三方庫(kù)。
Python 教程:
Python官方文檔:https://docs.python.org/3/tutorial/
Learn Python3 the Hard Way 中文版:https://wizardforcel.gitbooks.io/lpthw/content/
廖雪峰的 Python3 教程:https://www.liaoxuefeng.com/wiki/1016959663602400
- 文本處理基礎(chǔ)
在學(xué)習(xí)自然語(yǔ)言處理前,需要掌握文本處理的基礎(chǔ)知識(shí),包括正則表達(dá)式、字符編碼及文件操作等。
正則表達(dá)式教程:
菜鳥(niǎo)教程正則表達(dá)式:https://www.runoob.com/regexp/regexp-tutorial.html
Python正則表達(dá)式基本語(yǔ)法:https://www.runoob.com/python/python-reg-expressions.html
文件操作教程:
Python文件讀寫操作:https://www.runoob.com/python/python-files-io.html
Python文件操作手冊(cè):https://www.pythondoc.com/pythontutorial3/inputoutput.html
二、基礎(chǔ)操作
- 安裝 NLTK
安裝 NLTK 包,可以使用 pip 工具進(jìn)行安裝。
pip install nltk
- 下載 NLTK 數(shù)據(jù)集
NLTK 提供了多種語(yǔ)料庫(kù)、分類器和詞典數(shù)據(jù)集,包括 Brown Corpus、Gutenberg Corpus、WordNet 等,下面介紹如何下載數(shù)據(jù)集。
import nltk
nltk.download() # 下載所有語(yǔ)料庫(kù)和模型
nltk.download('stopwords') # 下載指定的語(yǔ)料庫(kù)
nltk.download('punkt') # 下載指定的語(yǔ)料庫(kù)
三、數(shù)據(jù)預(yù)處理
在進(jìn)行自然語(yǔ)言處理前,需要對(duì)文本進(jìn)行預(yù)處理,包括文本清洗、詞干提取、詞袋模型等操作。
- 文本清洗
文本清洗是指將文本中的噪聲、特殊字符等無(wú)用信息去除,將文本轉(zhuǎn)化為合適的格式進(jìn)行處理,包括去除標(biāo)點(diǎn)符號(hào)、轉(zhuǎn)換為小寫等操作。
- 分詞
將文本拆分為單詞或短語(yǔ)的過(guò)程稱為分詞,是進(jìn)行自然語(yǔ)言處理的第一步。
import nltk
# 將文本轉(zhuǎn)化為小寫
sequence = 'Hello, World!'
tokens = [word.lower() for word in nltk.word_tokenize(sequence)]
print(tokens) # ['hello', ',', 'world', '!']
- 詞干提取
將單詞的詞干提取出來(lái),是自然語(yǔ)言處理中的重要操作,它能夠?qū)⒉煌瑔卧~的 “干”( 或者說(shuō) 基礎(chǔ)形式)提取出來(lái)。
from nltk.stem import PorterStemmer
# 創(chuàng)建一個(gè)Porter stemmer object
porter = PorterStemmer()
# 進(jìn)行詞干提取
words = ["running","runner","runners","run","easily","fairly","fairness"]
for word in words:
print(porter.stem(word))
四、特征提取
在進(jìn)行自然語(yǔ)言處理時(shí),我們需要從文本中提取特征,然后將其用于分類、聚類、文本相似度比較等任務(wù)中。
- 詞袋模型
詞袋模型(Bag of Words,簡(jiǎn)稱 BoW),是將文本轉(zhuǎn)化為一組單詞以及單詞出現(xiàn)的頻率作為特征的一種方法。
from sklearn.feature_extraction.text import CountVectorizer
# 創(chuàng)建 CountVectorizer 對(duì)象
vectorizer = CountVectorizer()
# 將文本擬合到 CountVectorizer 中
corpus = [
'This is the first document.',
'This is the second second document.',
'And the third one.',
'Is this the first document?'
]
X = vectorizer.fit_transform(corpus)
# 打印特征值
print(vectorizer.get_feature_names())
# 打印詞袋模型中文本的向量化表示
print(X.toarray())
- TF-IDF 模型
TF-IDF(Term Frequency-Inverse Document Frequency)模型是一種評(píng)估單詞在文檔中重要性的方法,即單詞在文檔中出現(xiàn)的頻率越高,且同時(shí)在文檔庫(kù)中出現(xiàn)的頻率越低,則此單詞的重要性越大。
from sklearn.feature_extraction.text import TfidfVectorizer
import pandas as pd
# 創(chuàng)建 TfidfVectorizer 對(duì)象
tfidf_vec = TfidfVectorizer()
# 計(jì)算詞頻-逆向文本頻率
corpus = [
"This is the first document.",
"This is the second second document.",
"And the third one.",
"Is this the first document?"
]
tfidf_matrix = tfidf_vec.fit_transform(corpus)
# 打印特征值
print(tfidf_vec.get_feature_names())
# 打印詞袋模型中文本的向量化表示
print(pd.DataFrame(tfidf_matrix.toarray(), columns=tfidf_vec.get_feature_names()))
五、自然語(yǔ)言處理實(shí)踐
- 分類問(wèn)題
文本分類是將文本按照某種類別劃分的過(guò)程,是自然語(yǔ)言處理的一個(gè)重要任務(wù),例如:新聞分類、聊天機(jī)器人回復(fù)等。
import nltk
import pandas as pd
from nltk.tokenize import word_tokenize, sent_tokenize
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
# 讀取數(shù)據(jù)集
dataset = pd.read_csv("data.csv")
# 分詞
tokens = []
for index, row in dataset.iterrows():
text = row['text']
words = nltk.word_tokenize(text)
tokens.append(words)
# 獲得所有單詞的列表
all_words = []
for token in tokens:
for word in token:
all_words.append(word)
# 列表去重
all_words = nltk.FreqDist(all_words)
# 獲得前1000個(gè)常用單詞
word_features = list(all_words.keys())[:1000]
# 特征提取
def find_features(document):
words = set(document)
features = {}
for w in word_features:
features[w] = (w in words)
return features
featuresets = [(find_features(rev), category) for (rev, category) in zip(tokens, dataset['category'])]
# 劃分訓(xùn)練集和測(cè)試集
training_set, testing_set = train_test_split(featuresets, test_size=0.25, random_state=42)
# 訓(xùn)練模型
model = nltk.NaiveBayesClassifier.train(training_set)
# 打印準(zhǔn)確率
accuracy = nltk.classify.accuracy(model, testing_set)
print("Accuracy of the model: ", accuracy)
# 分類預(yù)測(cè)
predicted = [model.classify(features) for (features, category) in testing_set]
actual = [category for (features, category) in testing_set]
print("Classification Report:\n", nltk.classify.util.accuracy(model, testing_set))
- 相似度計(jì)算
文本相似度計(jì)算是指計(jì)算兩個(gè)文本之間的相似度,常用于信息檢索系統(tǒng)和推薦系統(tǒng)中。
import nltk
import pandas as pd
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from nltk.tokenize import word_tokenize
# 讀取數(shù)據(jù)集
dataset = pd.read_csv("data.csv")
# 預(yù)處理
texts = []
for text in dataset['text']:
words = word_tokenize(text)
texts.append(words)
# 進(jìn)行詞向量訓(xùn)練
documents = [TaggedDocument(doc, [i]) for i, doc in enumerate(texts)]
model = Doc2Vec(documents, vector_size=100, window=3, min_count=2, epochs=100)
# 計(jì)算文本相似度
text1 = "This is the first document."
text2 = "This is the second second document."
text3 = "And the third one."
text4 = "Is this the first document?"
text1_vec = model.infer_vector(word_tokenize(text1))
text2_vec = model.infer_vector(word_tokenize(text2))
text3_vec = model.infer_vector(word_tokenize(text3))
text4_vec = model.infer_vector(word_tokenize(text4))
print(nltk.cluster.util.cosine_distance(text1_vec, text2_vec))
print(nltk.cluster.util.cosine_distance(text1_vec, text3_vec))
print(nltk.cluster.util.cosine_distance(text1_vec, text4_vec))
六、學(xué)習(xí)資源
- 官方文檔
Python NLTK 官方文檔提供了詳盡的使用方法、示例和 API 文檔:http://www.nltk.org/
- NLTK 書(shū)籍
- 《Python自然語(yǔ)言處理》:講解了 NLTK 的基本用法和自然語(yǔ)言處理技術(shù),適合初學(xué)者閱讀。
- 《自然語(yǔ)言處理與文本挖掘》:介紹了自然語(yǔ)言處理的基本方法和技術(shù),并詳細(xì)講解了如何使用 Python 中的 NLTK 庫(kù)進(jìn)行自然語(yǔ)言處理。
- 《Python數(shù)據(jù)科學(xué)手冊(cè)》:介紹了如何使用 Python 進(jìn)行數(shù)據(jù)科學(xué)、機(jī)器學(xué)習(xí)和自然語(yǔ)言處理等任務(wù)。
- GitHub 示例
NLTK 官方文檔中提供了多個(gè)示例項(xiàng)目,也可以在 GitHub 上找到更多的 NLTK 示例:https://github.com/search?q=nltk&type=Repositories
- 博客文章
- 集成機(jī)器學(xué)習(xí)和自然語(yǔ)言處理——NLTK 使用指南:https://towardsdatascience.com/integrating-machine-learning-and-natural-language-processing-nltk-a552dd9ceb9a
- Python下利用NLTK進(jìn)行自然語(yǔ)言處理:https://zhuanlan.zhihu.com/p/33723365
- 自然語(yǔ)言處理(NLP)中最常用的 Python 庫(kù):https://towardsdatascience.com/the-most-used-python-libraries-for-nlp-5dcb388f024e
七、總結(jié)文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-468295.html
以上就是 Python NLTK 的學(xué)習(xí)路線和相關(guān)資料,從基礎(chǔ)知識(shí)到實(shí)際操作,希望可以幫助到想要學(xué)習(xí)自然語(yǔ)言處理的同學(xué), NLTK 是 Python 中為數(shù)不多的自然語(yǔ)言處理庫(kù)之一,可以幫助我們更好地預(yù)處理和處理文本數(shù)據(jù),同時(shí)也可以應(yīng)用于分類、相似度計(jì)算等任務(wù)中,是數(shù)據(jù)科學(xué)家和機(jī)器學(xué)習(xí)工程師不可或缺的工具之一。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-468295.html
到了這里,關(guān)于【Python NLTK】零基礎(chǔ)也能輕松掌握的學(xué)習(xí)路線與參考資料的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!