2015-04-15 108 views
4

對於一個項目,我想測量文本中「以人爲本」的詞的數量。我打算使用WordNet來完成這項工作。我從來沒有使用它,我不太清楚如何處理這個任務。我想使用WordNet來計算屬於某些同義詞的詞的數量,例如sysnets的「人」和「人」。WordNet:遍歷synsets

我想出了以下(簡單)的代碼:

word = 'girlfriend' 
word_synsets = wn.synsets(word)[0] 

hypernyms = word_synsets.hypernym_paths()[0] 

for element in hypernyms: 
    print element 

結果:

Synset('entity.n.01') 
Synset('physical_entity.n.01') 
Synset('causal_agent.n.01') 
Synset('person.n.01') 
Synset('friend.n.01') 
Synset('girlfriend.n.01') 

我的第一個問題是,如何正確遍歷上位?在上面的代碼中,它打印出來就好了。然而,當使用'if'語句時,例如:

count_humancenteredness = 0 
for element in hypernyms: 
    if element == 'person': 
     print 'found person hypernym' 
     count_humancenteredness +=1 

我得到'AttributeError:'str'對象沒有屬性'_name''。當一個詞確實屬於'人'或'人類'同義詞時,我可以使用什麼方法遍歷我的單詞的上位詞並執行動作(例如,增加人類中心的數量)。

其次,這是一種有效的方法嗎?我假設遍歷幾個文本並迭代每個名詞的上位詞將需要相當長的一段時間..也許還有另一種方式來使用WordNet來更有效地執行我的任務。

感謝您的幫助!

回答

4

WRT錯誤消息

hypernyms = word_synsets.hypernym_paths()返回SynSet的名單列表。

因此

if element == 'person': 

試圖以比較SynSet對象對的字符串。 SynSet不支持這種比較。

嘗試像

target_synsets = wn.synsets('person') 
if element in target_synsets: 
    ... 

if u'person' in element.lemma_names(): 
    ... 

代替。

WRT效率

目前,您的輸入文本中的每一個字做上位詞的查找。如您所見,這不一定有效。但是,如果速度足夠快,請停在此處,不要優化未破壞的內容。

爲了加快查找,您可以解釋here通過利用傳遞閉包在上下義詞預編譯提前「人相關」單詞的列表。

喜歡的東西

person_words = set(w for s in p.closure(lambda s: s.hyponyms()) for w in s.lemma_names()) 

應該做的伎倆。這將返回一組〜10,000單詞,這對於存儲在主存中並不太多。

字計數器的簡化版本則成爲對

from collections import Counter 

word_count = Counter() 
for word in (w.lower() for w in words if w in person_words):   
    word_count[word] += 1 

行可能還需要預先處理的東西用而產生或傳遞到WordNet的話先於其他形態的減少輸入的話,雖然。

0

爲了得到一個同義詞集合所有的下義詞,你可以使用以下function(與NLTK 3.0.3測試,dhke的關閉伎倆並不在此版本的工作):

def get_hyponyms(synset): 
    hyponyms = set() 
    for hyponym in synset.hyponyms(): 
     hyponyms |= set(get_hyponyms(hyponym)) 
    return hyponyms | set(synset.hyponyms()) 

例子:

from nltk.corpus import wordnet 
food = wordnet.synset('food.n.01') 
print(len(get_hyponyms(food))) # returns 1526