Search code examples
pythonnltkwordnet

Synsets for a word in WordNet


I am trying to work on finding Synsets in WordNet (which is Lexical database for English) using python.

Here is the code which I am trying to find synsets and example of that synsets (passed as parameter):

 from nltk.corpus import wordnet
synonynm=wordnet.synsets('friend')[2]#? wt does[0] mean
synonynm.name() #related synonyms wrds
synonynm.definition() #definition of passed words
wordnet.synsets('friend')[0].examples()

When I use index wordnet.synsets('friend')[0] or wordnet.synsets('friend')[1] or wordnet.synsets('friend')[2]

it gives me same output that can be viewed here

['he was my best friend at the university']

but if did place braces empty it showed error []

so i just want to know is the difference in uasge between

synonynm=wordnet.synsets('friend')[0]

and this

wordnet.synsets('friend')[1]

I would be grateful for your guidance


Solution

  • wordnet.synsets('friend') returns a list of Synsets:

    [Synset('friend.n.01'), Synset('ally.n.02'), Synset('acquaintance.n.03'), Synset('supporter.n.01'), Synset('friend.n.05')]
    

    You can then access each Synset in the list via its index eg. the first Synset in the list is:

    wordnet.synsets('friend')[0] # Synset('friend.n.01')
    wordnet.synsets('friend')[0].name() # friend.n.01
    wordnet.synsets('friend')[0].definition() # a person you know well and regard with affection and trust
    wordnet.synsets('friend')[0].examples() # ['he was my best friend at the university']
    

    Here's a code snippet that prints the name, definition and examples for each Synset in the list:

    from nltk.corpus import wordnet
    for result in wordnet.synsets('friend'):
        print(result.name(), result.definition(), result.examples())
    

    Output:

    friend.n.01 a person you know well and regard with affection and trust ['he was my best friend at the university']
    ally.n.02 an associate who provides cooperation or assistance ["he's a good ally in fight"]
    acquaintance.n.03 a person with whom you are acquainted ['I have trouble remembering the names of all my acquaintances', 'we are friends of the family']
    supporter.n.01 a person who backs a politician or a team etc. ['all their supporters came out for the game', 'they are friends of the library']
    friend.n.05 a member of the Religious Society of Friends founded by George Fox (the Friends have never called themselves Quakers) []
    

    Note that in your code, if you want the examples for index 2 in the list of Synsets, you should do:

    from nltk.corpus import wordnet
    synonynm=wordnet.synsets('friend')[2]
    synonynm.name() #related synonyms words
    synonynm.definition() #definition of passed words
    synonynm.examples()