natural language toolkit word sense disambiguation algorithms s liling tan alvationsgmail com dmitrijs milajevs dimazestgmail com c 20012023 nltk project url https www nltk org for license information see license txt return a synset for an ambiguous word in a context param iter contextsentence the context sentence where the ambiguous word occurs passed as an iterable of words param str ambiguousword the ambiguous word that requires wsd param str pos a specified partofspeech pos param iter synsets possible synsets of the ambiguous word param str lang wordnet language return lesksense the synset object with the highest signature overlaps this function is an implementation of the original lesk algorithm 1986 1 usage example lesk i went to the bank to deposit money bank n synset savingsbank n 02 1 lesk michael automatic sense disambiguation using machine readable dictionaries how to tell a pine cone from an ice cream cone proceedings of the 5th annual international conference on systems documentation acm 1986 https dl acm orgcitation cfm id318728 natural language toolkit word sense disambiguation algorithms s liling tan alvations gmail com dmitrijs milajevs dimazest gmail com c 2001 2023 nltk project url https www nltk org for license information see license txt return a synset for an ambiguous word in a context param iter context_sentence the context sentence where the ambiguous word occurs passed as an iterable of words param str ambiguous_word the ambiguous word that requires wsd param str pos a specified part of speech pos param iter synsets possible synsets of the ambiguous word param str lang wordnet language return lesk_sense the synset object with the highest signature overlaps this function is an implementation of the original lesk algorithm 1986 1 usage example lesk i went to the bank to deposit money bank n synset savings_bank n 02 1 lesk michael automatic sense disambiguation using machine readable dictionaries how to tell a pine cone from an ice cream cone proceedings of the 5th annual international conference on systems documentation acm 1986 https dl acm org citation cfm id 318728
from nltk.corpus import wordnet


def lesk(context_sentence, ambiguous_word, pos=None, synsets=None, lang="eng"):
    

    context = set(context_sentence)
    if synsets is None:
        synsets = wordnet.synsets(ambiguous_word, lang=lang)

    if pos:
        synsets = [ss for ss in synsets if str(ss.pos()) == pos]

    if not synsets:
        return None

    _, sense = max(
        (len(context.intersection(ss.definition().split())), ss) for ss in synsets
    )

    return sense