python nltk 基本操作

2021-07-01 23:48:58 字數 1510 閱讀 8579

nltk.sent_tokenize(text) #按句子分割

nltk.word_tokenize(sentence) #分詞

nltk的分詞是句子級別的,所以對於一篇文件首先要將文章按句子進行分割,然後句子進行分詞

nltk.pos_tag(tokens) #對分詞後的句子進行詞性標註

tags = [nltk.pos_tag(tokens) for tokens in words]

>>>tags

[[('this', 'dt'), ('is', 'vbz'), ('a', 'dt'), ('text', 'nn'), ('for', 'in'), ('test', 'nn'), ('.', '.')], [('and', 'cc'), ('i', 'prp'), ('want', 'vbp'), ('to', 'to'), ('learn', 'vb'), ('how', 'wrb'), ('to', 'to'), ('use', 'vb'), ('nltk', 'nn'), ('.', '.')]]

用於實體識別的基本技術是分塊,可以理解為把對個token組成片語。

np-chunking,尋找單獨名詞短語對應的塊。為了建立np分塊,首先需要定義分塊語法,規定句子如何分塊。下面使用的是乙個簡單的正則,這條規則規定由可選的且後面跟著任意數量形容詞(jj)的限定詞(dj)和名詞(nn)組成。

>>> text = "the little yellow dog barked at the cat"

>>> sentence = nltk.word_tokenize(text)

>>> sentence = nltk.pos_tag(sentence)

>>> sentence

[('the', 'dt'), ('little', 'jj'), ('yellow', 'nn'), ('dog', 'nn'), ('barked', 'vbd'), ('at', 'in'), ('the', 'dt'), ('cat', 'nn')]

>>> grammar = "np: "

>>> cp = nltk.regexpparser(grammar)

>>> result = cp.parse(sentence)

>>> result

tree('s', [tree('np', [('the', 'dt'), ('little', 'jj'), ('yellow', 'nn')]), tree('np', [('dog', 'nn')]), ('barked', 'vbd'), ('at', 'in'), tree('np', [('the', 'dt'), ('cat', 'nn')])])

>>> result.draw()

ref:

python NLTK 環境搭建

這裡是我之前親自操作過安裝nltk,安裝成功了。當時記得是參考這篇博文 1.安裝python 我安裝的是python2.7.8,目錄d python27 2.安裝numpy 可選 注意py版本 把nltk 3.0.0解壓到d python27目錄 開啟cmd,進到d python27 nltk 3....

Python NLTK環境搭建

for 32 bits windows 1.安裝python 我安裝的是python2.7,目錄c python27 2.安裝numpy 可選 注意py版本 把nltk 2.0.3解壓到c python27目錄 開啟cmd,進到c python27 nltk 2.0.3目錄 輸入 cd c pyth...

Python NLTK提取有用的chunk

文字的資訊很多,我們需要如何提取有用的資訊?比如一句話 json is a good boy 我們希望得到的資訊是json 和 a good boy 那麼首先我們需要對句子進行分詞和判斷單詞的屬性 可以用下面的 def ie preprocess document sentences nltk.se...