对于一个项目,我想测量文本中“以人为中心”单词的数量。我计划使用WordNet来完成这个任务。我从未使用过它,我也不太清楚该如何完成这项任务。我想使用WordNet来计算属于某些同步集的单词数量,例如sysnet‘human’和‘person’。
我想出了以下(简单)代码:
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’。当一个词确实属于‘person’或‘human’synset时,我可以使用什么方法来迭代我的单词的超限,并执行一个动作(例如,增加人类中心的数量)。
第二,这是否一个有效的方法?我假设迭代几个文本并迭代每个名词的超数词将需要相当长的时间。也许还有另一种方法可以使用WordNet来更有效地执行我的任务。
谢谢你的帮忙!
发布于 2015-04-15 11:28:44
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之前,您可能还需要使用词干或其他形态缩减对输入单词进行预处理。
发布于 2015-12-02 05:09:31
要获得一个同步集的所有下义词,您可以使用以下function (用NLTK3.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 1526https://stackoverflow.com/questions/29647068
复制相似问题