2015-10-08 43 views
0

我不是Python的專家,我只是嘗試幾個算法。使用正則表達式和POS提取名詞和實體

我有一個句子,例如,

"The maker of Sam Global Ent, Sam Helsen has bought many stocks in a private intelligence firm Samligence." 

我試圖用POS-惡搞讓所有的名詞,但是,如果的強校實體以一個大寫字母,他們應該被視爲一個實體開始。

例如:「Sam Global Ent」應被視爲一個實體。

我找的輸出如下:

[u'maker',      -- Noun 
u'Sam Global Ent',   -- Considered as one entity 
u'Sam Helsen',    -- Considered as one entity 
u'stocks',     -- Noun 
u'intelligence',    -- Noun 
u'firm',      -- Noun 
u'Samligence']    -- Noun/entity 

我寫的代碼seperately兩者都做的工作,但我不知道如何將它們的性能有效的方式結合起來。

我寫到目前爲止是代碼..

對於Extrating開始用大寫字母的強校實體:

find_entities=re.findall(r'\b[A-Z]\w+(?:\s\b[A-Z]\w+)*', sentences, re.DOTALL) 

輸出:

find_entities= ['The', 'Sam Global Ent', 'Sam Helsen', 'Samligence'] 

用於提取所有名詞:

words=word_tokenize(sentences.decode('utf-8')) 
    for pos in pos_tag(words): 
     if 'NN' in pos[1]: 
      entity_nouns.append(pos[0]) 

輸出:

entity_nouns= 
[u'maker', 
u'Sam', 
u'Global', 
u'Ent', 
u'Sam', 
u'Helsen', 
u'stocks', 
u'intelligence', 
u'firm', 
u'Samligence'] 

我想過像交集的方法。例如,將「find_entities」分解爲單個元素(['The','Sam','Global','Ent','Sam','Helsen','Samligence']),然後將其減去entity_nouns,然後添加再次得到find_entities。但這似乎是一個非常漫長的過程。

如果有人能幫助我,我會很高興。

回答

1

已嘗試過TextBlob?它提取了名詞短語:

>>> from textblob import TextBlob 
>>> txt = """The maker of Sam Global Ent, Sam Helsen has bought many stocks in a private intelligence firm Samligence.""" 
>>> blob = TextBlob(txt) 
>>> blob.noun_phrases 
WordList([u'sam global ent', u'sam helsen', u'private intelligence firm', 'samligence']) 
+0

謝謝,這真的很有幫助。 – Sam

2

考慮一個簡單的方法:您已經將該句子標記爲單詞。代替正則表達式的方法來查找實體,只需對字詞列表進行一次迭代,然後合併列表中以大寫字母開頭的連續字詞。

+0

哎喲,但那樣會夠快嗎?通常預定義的函數,如「正則表達式」,「交集(使用集合)」,「聯合」等與包括遍歷每個單詞的方法相比是快速的。 – Sam

+0

我覺得如果沒有真正測量它就很難比較。正則表達式也不是免費的。無論如何,除非你期望列表迭代執行_ridiculously_壞,我會認爲這是「不成熟的優化」。 – matz