1. 程式人生 > >python自然語言處理——NLTK——詞性標籤(pos_tag)

python自然語言處理——NLTK——詞性標籤(pos_tag)

  • 最近在做一個分類40000條推特評論的情感分類器。
  • 設計文字情感分類器的時候首先要用到的就是NLTK包來進行單詞過濾。

先用NLTK包的pos_tag方法(part-of-speech tagging)來對單詞的詞性進行標記,標記後的結果是二元陣列格式。之後從這個二元數列中挑出我們所有需要的tag,存放進一個二元數列。

  • 實現程式碼:

首先別忘了

import nltk

假設我們處理的是like hate這兩個詞。任意選擇一段英語文字,建立它們的token

words=word_tokenize(‘i hate study on monday. Jim like rabbit.’)

然後挑選出所有需要的詞性。詞性列表:

CC     coordinatingconjunction 並列連詞

CD     cardinaldigit  純數基數

DT     determiner  限定詞(置於名詞前起限定作用,如 thesomemy 等)

EX     existentialthere (like:"there is"... think of it like "thereexists")   存在句;存現句

FW     foreignword  外來語;外來詞;外文原詞

IN     preposition/subordinating conjunction介詞/從屬連詞;主從連詞;從屬連線詞

JJ     adjective   

'big'  形容詞

JJR    adjective, comparative 'bigger' (形容詞或副詞的)比較級形式

JJS    adjective, superlative 'biggest'  (形容詞或副詞的)最高階

LS     listmarker  1)

MD     modal (could, will) 形態的,形式的 , 語氣的;情態的

NN     noun, singular 'desk' 名詞單數形式

NNS    nounplural  'desks'  名詞複數形式

NNP    propernoun, singular     'Harrison' 專有名詞

NNPS  proper noun

, plural 'Americans'  專有名詞複數形式

PDT    predeterminer      'all the kids'  前位限定詞

POS    possessiveending  parent's   屬有詞結束語

PRP    personalpronoun   I, he, she  人稱代詞

PRP$  possessive pronoun my, his, hers  物主代詞

RB     adverb very, silently, 副詞非常靜靜地

RBR    adverb,comparative better   (形容詞或副詞的)比較級形式

RBS    adverb,superlative best    (形容詞或副詞的)最高階

RP     particle     give up 小品詞(與動詞構成短語動詞的副詞或介詞)

TO     to    go 'to' the store.

UH     interjection errrrrrrrm  感嘆詞;感嘆語

VB     verb, baseform    take   動詞

VBD    verb, pasttense   took   動詞過去時;過去式

VBG    verb,gerund/present participle taking 動詞動名詞/現在分詞

VBN    verb, pastparticiple     taken 動詞過去分詞

VBP    verb,sing. present, non-3d     take 動詞現在

VBZ    verb, 3rdperson sing. present  takes   動詞第三人稱

WDT    wh-determiner      which 限定詞(置於名詞前起限定作用,如 thesomemy 等)

WP     wh-pronoun   who, what 代詞(代替名詞或名詞片語的單詞)

WP$    possessivewh-pronoun     whose  所有格;屬有詞

WRB    wh-abverb    where, when 副詞

(https://wenku.baidu.com/view/c63bec3b366baf1ffc4ffe4733687e21af45ffab.html)

因為情感分類,一般需要的是人稱代詞、動詞、形容詞、副詞等,所以挑選出合適的tags;並且把pos_tag方法建立的詞和對應詞性儲存在pos_tags數列。

tags = set(['MD', 'UH', 'VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ', 'RP', 'RB', 'RBR', 'RBS', 'JJ', 'JJR', 'JJS'])
pos_tags =nltk.pos_tag(words)

之後建立空陣列ret,遍歷pos_tags,把有我們需要的詞性的陣列儲存到ret[]

ret = []
for word,pos in pos_tags:
        if (pos in tags):
            ret.append(word)
 return ' '.join(ret)