wordnet semantic similarity: how to refer to elements of a pair in a list? can we sort dictionary according to the value?

alex23 wuwei23 at gmail.com
Mon Oct 8 23:31:38 EDT 2012


On Oct 9, 1:13 pm, Token Type <typeto... at gmail.com> wrote:
> yes, thanks all your tips. I did try sorted with itemgetter.
> However, the sorted results are same as follows whether I
> set reverse=True or reverse= False. Isn't it strange? Thanks.

That's because you're sorting each entry individually, not the entire
result. For every key-value pair, you create a new empty list, append
one tuple, and then sort it. The consistent order you're seeing is the
outcome of stepping through the dictionary keys.

This is untested, but it should be closer to what you're after, I
think. First it creates `list_simi` as a generator, then it sorts it.

    import nltk
    from nltk.corpus import wordnet as wn
    from operator import itemgetter

    pairs = {'car':'automobile', 'gem':'jewel', 'journey':'voyage'}

    def find_similarity(word1, word2):
        as_synset = lambda word: wn.synset( str(word) + '.n.01' )
        return as_synset(word1).path_similarity( as_synset(word2) )

    similarity_value = itemgetter(1)

    list_simi = (
        ('%s-%s' % (word1, word2), find_similarity(word1, word2) )
        for word1, word2 in pairs.iteritems()
    )
    list_simi = sorted(list_simi, key=similarity_value, reverse=True)



More information about the Python-list mailing list