用于Synset1._shortest_path_distance(Synset2)
查找上位词及其距离:
>>> from nltk.corpus import wordnet as wn
>>> alaska = wn.synset('Alaska.n.1')
>>> california = wn.synset('California.n.1')
>>> alaska._shortest_hypernym_paths(california)
{Synset('district.n.01'): 4, Synset('location.n.01'): 6, Synset('region.n.03'): 5, Synset('physical_entity.n.01'): 8, Synset('entity.n.01'): 9, Synset('state.n.01'): 2, Synset('administrative_district.n.01'): 3, Synset('object.n.01'): 7, Synset('alaska.n.01'): 0, Synset('*ROOT*'): 10, Synset('american_state.n.01'): 1}
现在找到最小路径:
>>> paths = alaska._shortest_hypernym_paths(california)
>>> min(paths, key=paths.get)
Synset('alaska.n.01')
现在,这很无聊,因为california
和alaska
是 WordNet 层次结构上的姐妹节点。让我们过滤掉所有姐妹节点:
>>> paths = {k:v for k,v in paths.items() if v > 0}
>>> min(paths, key=paths.get)
Synset('american_state.n.01')
要获得的子节点american_state
(我想这是你需要的“很棒的东西”......):
>>> min(paths, key=paths.get).hyponyms()
[Synset('free_state.n.02'), Synset('slave_state.n.01')]
>>> list(min(paths, key=paths.get).closure(lambda s:s.hyponyms()))
[Synset('free_state.n.02'), Synset('slave_state.n.01')]
这可能看起来令人震惊,但实际上,没有表示alaska
or的上位词california
:
>>> alaska.hypernyms()
[]
>>> california.hypernyms()
[]
并且使用 d 建立的连接_shortest_hypernym_paths
是通过虚拟根进行的,看看Wordnet 路径相似性可交换吗?