【问题标题】:WordNet: Iterate over synsetsWordNet:迭代同义词集
【发布时间】:2015-12-02 13:09:31
【问题描述】:

对于一个项目,我想测量文本中“以人为本”单词的数量。我打算用 WordNet 来做这件事。我从未使用过它,我不太确定如何完成这项任务。我想使用 WordNet 来计算属于某些同义词集的词的数量,例如 sysnets ‘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''。当一个词确实属于“人”或“人”同义词集时,我可以使用什么方法来迭代我的词的上位词并执行一个动作(例如增加人类中心性的计数)。

其次,这是一种有效的方法吗?我假设遍历多个文本并遍历每个名​​词的上位词将需要相当长的时间。也许还有另一种方法可以使用 WordNet 更有效地执行我的任务。

感谢您的帮助!

【问题讨论】:

    标签: python nltk wordnet


    【解决方案1】:

    写错误信息

    hypernyms = word_synsets.hypernym_paths() 返回SynSets 的列表。

    因此

    if element == 'person':
    

    尝试将SynSet 对象与字符串进行比较。 SynSet 不支持这种比较。

    试试类似的东西

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

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

    改为。

    效率

    目前,您对输入文本中的每个单词进行上位词查找。正如您所注意到的,这不一定是有效的。但是,如果这足够快,请在此停止,不要优化未损坏的部分。

    为了加快查找速度,您可以使用 here 解释的下位词上的传递闭包提前预编译“person related”单词列表。

    类似

    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。

    【讨论】:

      【解决方案2】:

      要获取同义词集的所有下位词,您可以使用以下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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多