淺談Python NLP入門教程
正文
本文簡要介紹Python自然語言處理(NLP),使用Python的NLTK庫。NLTK是Python的自然語言處理工具包,在NLP領(lǐng)域中,最常使用的一個Python庫。
什么是NLP?
簡單來說,自然語言處理(NLP)就是開發(fā)能夠理解人類語言的應(yīng)用程序或服務(wù)。
這里討論一些自然語言處理(NLP)的實際應(yīng)用例子,如語音識別、語音翻譯、理解完整的句子、理解匹配詞的同義詞,以及生成語法正確完整句子和段落。
這并不是NLP能做的所有事情。
NLP實現(xiàn)
搜索引擎: 比如谷歌,Yahoo等。谷歌搜索引擎知道你是一個技術(shù)人員,所以它顯示與技術(shù)相關(guān)的結(jié)果;
社交網(wǎng)站推送:比如Facebook News Feed。如果News Feed算法知道你的興趣是自然語言處理,就會顯示相關(guān)的廣告和帖子。
語音引擎:比如Apple的Siri。
垃圾郵件過濾:如谷歌垃圾郵件過濾器。和普通垃圾郵件過濾不同,它通過了解郵件內(nèi)容里面的的深層意義,來判斷是不是垃圾郵件。
NLP庫
下面是一些開源的自然語言處理庫(NLP):
- Natural language toolkit (NLTK);
- Apache OpenNLP;
- Stanford NLP suite;
- Gate NLP library
其中自然語言工具包(NLTK)是最受歡迎的自然語言處理庫(NLP),它是用Python編寫的,而且背后有非常強(qiáng)大的社區(qū)支持。
NLTK也很容易上手,實際上,它是最簡單的自然語言處理(NLP)庫。
在這個NLP教程中,我們將使用Python NLTK庫。
安裝 NLTK
如果您使用的是Windows/Linux/Mac,您可以使用pip安裝NLTK:
pip install nltk
打開python終端導(dǎo)入NLTK檢查NLTK是否正確安裝:
import nltk
如果一切順利,這意味著您已經(jīng)成功地安裝了NLTK庫。首次安裝了NLTK,需要通過運(yùn)行以下代碼來安裝NLTK擴(kuò)展包:
import nltk nltk.download()
這將彈出NLTK 下載窗口來選擇需要安裝哪些包:
您可以安裝所有的包,因為它們的大小都很小,所以沒有什么問題。
使用Python Tokenize文本
首先,我們將抓取一個web頁面內(nèi)容,然后分析文本了解頁面的內(nèi)容。
我們將使用urllib模塊來抓取web頁面:
import urllib.request response = urllib.request.urlopen('http://php.net/') html = response.read() print (html)
從打印結(jié)果中可以看到,結(jié)果包含許多需要清理的HTML標(biāo)簽。
然后BeautifulSoup模塊來清洗這樣的文字:
from bs4 import BeautifulSoup import urllib.request response = urllib.request.urlopen('http://php.net/') html = response.read() soup = BeautifulSoup(html,"html5lib") # 這需要安裝html5lib模塊 text = soup.get_text(strip=True) print (text)
現(xiàn)在我們從抓取的網(wǎng)頁中得到了一個干凈的文本。
下一步,將文本轉(zhuǎn)換為tokens,像這樣:
from bs4 import BeautifulSoup import urllib.request response = urllib.request.urlopen('http://php.net/') html = response.read() soup = BeautifulSoup(html,"html5lib") text = soup.get_text(strip=True) tokens = text.split() print (tokens)
統(tǒng)計詞頻
text已經(jīng)處理完畢了,現(xiàn)在使用Python NLTK統(tǒng)計token的頻率分布。
可以通過調(diào)用NLTK中的FreqDist()方法實現(xiàn):
from bs4 import BeautifulSoup import urllib.request import nltk response = urllib.request.urlopen('http://php.net/') html = response.read() soup = BeautifulSoup(html,"html5lib") text = soup.get_text(strip=True) tokens = text.split() freq = nltk.FreqDist(tokens) for key,val in freq.items(): print (str(key) + ':' + str(val))
如果搜索輸出結(jié)果,可以發(fā)現(xiàn)最常見的token是PHP。
您可以調(diào)用plot函數(shù)做出頻率分布圖:
freq.plot(20, cumulative=False) # 需要安裝matplotlib庫
這上面這些單詞。比如of,a,an等等,這些詞都屬于停用詞。
一般來說,停用詞應(yīng)該刪除,防止它們影響分析結(jié)果。
處理停用詞
NLTK自帶了許多種語言的停用詞列表,如果你獲取英文停用詞:
from nltk.corpus import stopwords stopwords.words('english')
現(xiàn)在,修改下代碼,在繪圖之前清除一些無效的token:
clean_tokens = list() sr = stopwords.words('english') for token in tokens: if token not in sr: clean_tokens.append(token)
最終的代碼應(yīng)該是這樣的:
from bs4 import BeautifulSoup import urllib.request import nltk from nltk.corpus import stopwords response = urllib.request.urlopen('http://php.net/') html = response.read() soup = BeautifulSoup(html,"html5lib") text = soup.get_text(strip=True) tokens = text.split() clean_tokens = list() sr = stopwords.words('english') for token in tokens: if not token in sr: clean_tokens.append(token) freq = nltk.FreqDist(clean_tokens) for key,val in freq.items(): print (str(key) + ':' + str(val))
現(xiàn)在再做一次詞頻統(tǒng)計圖,效果會比之前好些,因為剔除了停用詞:
freq.plot(20,cumulative=False)
使用NLTK Tokenize文本
在之前我們用split方法將文本分割成tokens,現(xiàn)在我們使用NLTK來Tokenize文本。
文本沒有Tokenize之前是無法處理的,所以對文本進(jìn)行Tokenize非常重要的。token化過程意味著將大的部件分割為小部件。
你可以將段落tokenize成句子,將句子tokenize成單個詞,NLTK分別提供了句子tokenizer和單詞tokenizer。
假如有這樣這段文本:
Hello Adam, how are you? I hope everything is going well. Today is a good day, see you dude.
使用句子tokenizer將文本tokenize成句子:
from nltk.tokenize import sent_tokenize mytext = "Hello Adam, how are you? I hope everything is going well. Today is a good day, see you dude." print(sent_tokenize(mytext))
輸出如下:
['Hello Adam, how are you?', 'I hope everything is going well.', 'Today is a good day, see you dude.']
這是你可能會想,這也太簡單了,不需要使用NLTK的tokenizer都可以,直接使用正則表達(dá)式來拆分句子就行,因為每個句子都有標(biāo)點和空格。
那么再來看下面的文本:
Hello Mr. Adam, how are you? I hope everything is going well. Today is a good day, see you dude.
這樣如果使用標(biāo)點符號拆分,Hello Mr將會被認(rèn)為是一個句子,如果使用NLTK:
from nltk.tokenize import sent_tokenize mytext = "Hello Mr. Adam, how are you? I hope everything is going well. Today is a good day, see you dude." print(sent_tokenize(mytext))
輸出如下:
['Hello Mr. Adam, how are you?', 'I hope everything is going well.', 'Today is a good day, see you dude.']
這才是正確的拆分。
接下來試試單詞tokenizer:
from nltk.tokenize import word_tokenize mytext = "Hello Mr. Adam, how are you? I hope everything is going well. Today is a good day, see you dude." print(word_tokenize(mytext))
輸出如下:
['Hello', 'Mr.', 'Adam', ',', 'how', 'are', 'you', '?', 'I', 'hope', 'everything', 'is', 'going', 'well', '.', 'Today', 'is', 'a', 'good', 'day', ',', 'see', 'you', 'dude', '.']
Mr.這個詞也沒有被分開。NLTK使用的是punkt模塊的PunktSentenceTokenizer,它是NLTK.tokenize的一部分。而且這個tokenizer經(jīng)過訓(xùn)練,可以適用于多種語言。
非英文Tokenize
Tokenize時可以指定語言:
from nltk.tokenize import sent_tokenize mytext = "Bonjour M. Adam, comment allez-vous? J'espère que tout va bien. Aujourd'hui est un bon jour." print(sent_tokenize(mytext,"french"))
輸出結(jié)果如下:
['Bonjour M. Adam, comment allez-vous?', "J'espère que tout va bien.", "Aujourd'hui est un bon jour."]
同義詞處理
使用nltk.download()安裝界面,其中一個包是WordNet。
WordNet是一個為自然語言處理而建立的數(shù)據(jù)庫。它包括一些同義詞組和一些簡短的定義。
您可以這樣獲取某個給定單詞的定義和示例:
from nltk.corpus import wordnet syn = wordnet.synsets("pain") print(syn[0].definition()) print(syn[0].examples())
輸出結(jié)果是:
a symptom of some physical hurt or disorder
['the patient developed severe pain and distension']
WordNet包含了很多定義:
from nltk.corpus import wordnet syn = wordnet.synsets("NLP") print(syn[0].definition()) syn = wordnet.synsets("Python") print(syn[0].definition())
結(jié)果如下:
the branch of information science that deals with natural language information
large Old World boas
可以像這樣使用WordNet來獲取同義詞:
from nltk.corpus import wordnet synonyms = [] for syn in wordnet.synsets('Computer'): for lemma in syn.lemmas(): synonyms.append(lemma.name()) print(synonyms)
輸出:
['computer', 'computing_machine', 'computing_device', 'data_processor', 'electronic_computer', 'information_processing_system', 'calculator', 'reckoner', 'figurer', 'estimator', 'computer']
反義詞處理
也可以用同樣的方法得到反義詞:
from nltk.corpus import wordnet antonyms = [] for syn in wordnet.synsets("small"): for l in syn.lemmas(): if l.antonyms(): antonyms.append(l.antonyms()[0].name()) print(antonyms)
輸出:
['large', 'big', 'big']
詞干提取
語言形態(tài)學(xué)和信息檢索里,詞干提取是去除詞綴得到詞根的過程,例如working的詞干為work。
搜索引擎在索引頁面時就會使用這種技術(shù),所以很多人為相同的單詞寫出不同的版本。
有很多種算法可以避免這種情況,最常見的是波特詞干算法。NLTK有一個名為PorterStemmer的類,就是這個算法的實現(xiàn):
from nltk.stem import PorterStemmer stemmer = PorterStemmer() print(stemmer.stem('working')) print(stemmer.stem('worked'))
輸出結(jié)果是:
work
work
還有其他的一些詞干提取算法,比如 Lancaster詞干算法。
非英文詞干提取
除了英文之外,SnowballStemmer還支持13種語言。
支持的語言:
from nltk.stem import SnowballStemmer print(SnowballStemmer.languages) 'danish', 'dutch', 'english', 'finnish', 'french', 'german', 'hungarian', 'italian', 'norwegian', 'porter', 'portuguese', 'romanian', 'russian', 'spanish', 'swedish'
你可以使用SnowballStemmer類的stem函數(shù)來提取像這樣的非英文單詞:
from nltk.stem import SnowballStemmer french_stemmer = SnowballStemmer('french') print(french_stemmer.stem("French word"))
單詞變體還原
單詞變體還原類似于詞干,但不同的是,變體還原的結(jié)果是一個真實的單詞。不同于詞干,當(dāng)你試圖提取某些詞時,它會產(chǎn)生類似的詞:
from nltk.stem import PorterStemmer stemmer = PorterStemmer() print(stemmer.stem('increases'))
結(jié)果:
increas
現(xiàn)在,如果用NLTK的WordNet來對同一個單詞進(jìn)行變體還原,才是正確的結(jié)果:
from nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer() print(lemmatizer.lemmatize('increases'))
結(jié)果:
increase
結(jié)果可能會是一個同義詞或同一個意思的不同單詞。
有時候?qū)⒁粋€單詞做變體還原時,總是得到相同的詞。
這是因為語言的默認(rèn)部分是名詞。要得到動詞,可以這樣指定:
from nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer() print(lemmatizer.lemmatize('playing', pos="v"))
結(jié)果:
play
實際上,這也是一種很好的文本壓縮方式,最終得到文本只有原先的50%到60%。
結(jié)果還可以是動詞(v)、名詞(n)、形容詞(a)或副詞(r):
from nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer() print(lemmatizer.lemmatize('playing', pos="v")) print(lemmatizer.lemmatize('playing', pos="n")) print(lemmatizer.lemmatize('playing', pos="a")) print(lemmatizer.lemmatize('playing', pos="r"))
輸出:
play
playing
playing
playing
詞干和變體的區(qū)別
通過下面例子來觀察:
from nltk.stem import WordNetLemmatizer from nltk.stem import PorterStemmer stemmer = PorterStemmer() lemmatizer = WordNetLemmatizer() print(stemmer.stem('stones')) print(stemmer.stem('speaking')) print(stemmer.stem('bedroom')) print(stemmer.stem('jokes')) print(stemmer.stem('lisa')) print(stemmer.stem('purple')) print('----------------------') print(lemmatizer.lemmatize('stones')) print(lemmatizer.lemmatize('speaking')) print(lemmatizer.lemmatize('bedroom')) print(lemmatizer.lemmatize('jokes')) print(lemmatizer.lemmatize('lisa')) print(lemmatizer.lemmatize('purple'))
輸出:
stone
speak
bedroom
joke
lisa
purpl
---------------------
stone
speaking
bedroom
joke
lisa
purple
詞干提取不會考慮語境,這也是為什么詞干提取比變體還原快且準(zhǔn)確度低的原因。
個人認(rèn)為,變體還原比詞干提取更好。單詞變體還原返回一個真實的單詞,即使它不是同一個單詞,也是同義詞,但至少它是一個真實存在的單詞。
如果你只關(guān)心速度,不在意準(zhǔn)確度,這時你可以選用詞干提取。
在此NLP教程中討論的所有步驟都只是文本預(yù)處理。在以后的文章中,將會使用Python NLTK來實現(xiàn)文本分析。
我已經(jīng)盡量使文章通俗易懂。希望能對你有所幫助。也希望大家多多支持腳本之家。
相關(guān)文章
Python?設(shè)計模式創(chuàng)建型單例模式
這篇文章主要介紹了Python?設(shè)計模式創(chuàng)建型單例模式,即Singleton,單例是一種設(shè)計模式,應(yīng)用該模式的類只會生成一個實例,下文詳細(xì)介紹需要的小伙伴可以參考一下2022-02-02python使用JSON模塊進(jìn)行數(shù)據(jù)處理(編碼解碼)
這篇文章主要為大家介紹了python使用JSON模塊進(jìn)行數(shù)據(jù)處理編碼解碼的使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06PyCharm搭建Spark開發(fā)環(huán)境的實現(xiàn)步驟
這篇文章主要介紹了PyCharm搭建Spark開發(fā)環(huán)境的實現(xiàn)步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09如何用 Python 子進(jìn)程關(guān)閉 Excel 自動化中的彈窗
這篇文章主要介紹了如何用 Python 子進(jìn)程關(guān)閉 Excel 自動化中的彈窗,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下2021-05-05Anaconda中Python虛擬環(huán)境的創(chuàng)建使用與刪除方法詳解
這篇文章主要為大家介紹了在Anaconda環(huán)境下,創(chuàng)建、使用與刪除Python虛擬環(huán)境的方法,具有一定的借鑒價值,需要的小伙伴可以跟隨小編一起了解一下2023-08-08