Python nltk.corpus.wordnet.synset() Examples

The following are 30 code examples for showing how to use nltk.corpus.wordnet.synset(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module nltk.corpus.wordnet , or try the search function .

Example 1
Project: razzy-spinner   Author: rafasashi   File: wordnet_app.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_static_welcome_message():
    """
    Get the static welcome page.
    """
    return \
"""
<h3>Search Help</h3>
<ul><li>The display below the line is an example of the output the browser
shows you when you enter a search word. The search word was <b>green</b>.</li>
<li>The search result shows for different parts of speech the <b>synsets</b>
i.e. different meanings for the word.</li>
<li>All underlined texts are hypertext links. There are two types of links:
word links and others. Clicking a word link carries out a search for the word
in the Wordnet database.</li>
<li>Clicking a link of the other type opens a display section of data attached
to that link. Clicking that link a second time closes the section again.</li>
<li>Clicking <u>S:</u> opens a section showing the relations for that synset.</li>
<li>Clicking on a relation name opens a section that displays the associated
synsets.</li>
<li>Type a search word in the <b>Next Word</b> field and start the search by the
<b>Enter/Return</b> key or click the <b>Search</b> button.</li>
</ul>
""" 
Example 2
Project: razzy-spinner   Author: rafasashi   File: sentiwordnet.py    License: GNU General Public License v3.0 6 votes vote down vote up
def senti_synset(self, *vals):        
        from nltk.corpus import wordnet as wn
        if tuple(vals) in self._db:
            pos_score, neg_score = self._db[tuple(vals)]
            pos, offset = vals
            synset = wn._synset_from_pos_and_offset(pos, offset)
            return SentiSynset(pos_score, neg_score, synset)
        else:
            synset = wn.synset(vals[0])
            pos = synset.pos()
            offset = synset.offset()
            if (pos, offset) in self._db:
                pos_score, neg_score = self._db[(pos, offset)]
                return SentiSynset(pos_score, neg_score, synset)
            else:
                return None 
Example 3
Project: Context-aware-ZSR   Author: ruotianluo   File: convert_gcn.py    License: MIT License 6 votes vote down vote up
def get_synset_embedding(synset, word_vectors, get_vector):
    class_name = wn.synset(synset).lemma_names()
    class_name = ', '.join([_.replace('_', ' ') for _ in class_name])
    class_name = class_name.lower()

    feat = np.zeros(feat_len)

    options = class_name.split(',')
    cnt_word = 0
    for j in range(len(options)):
        now_feat = get_embedding(options[j].strip(), word_vectors, get_vector)
        if np.abs(now_feat.sum()) > 0:
            cnt_word += 1
            feat += now_feat
    if cnt_word > 0:
        feat = feat / cnt_word

    if np.abs(feat.sum()) == 0:
        return feat
    else:
        # feat = feat / (np.linalg.norm(feat) + 1e-6)
        return feat 
Example 4
Project: Context-aware-ZSR   Author: ruotianluo   File: convert_sync.py    License: MIT License 6 votes vote down vote up
def get_synset_embedding(synset, word_vectors, get_vector):
    class_name = wn.synset(synset).lemma_names()
    class_name = ', '.join([_.replace('_', ' ') for _ in class_name])
    class_name = class_name.lower()

    feat = np.zeros(feat_len)

    options = class_name.split(',')
    cnt_word = 0
    for j in range(len(options)):
        now_feat = get_embedding(options[j].strip(), word_vectors, get_vector)
        if np.abs(now_feat.sum()) > 0:
            cnt_word += 1
            feat += now_feat
    if cnt_word > 0:
        feat = feat / cnt_word

    if np.abs(feat.sum()) == 0:
        return feat
    else:
        # feat = feat / (np.linalg.norm(feat) + 1e-6)
        return feat 
Example 5
Project: Context-aware-ZSR   Author: ruotianluo   File: convert_from_bansal.py    License: MIT License 6 votes vote down vote up
def get_synset_embedding(synset, word_vectors, get_vector):
    class_name = wn.synset(synset).lemma_names()
    class_name = ', '.join([_.replace('_', ' ') for _ in class_name])
    class_name = class_name.lower()

    feat = np.zeros(feat_len)

    options = class_name.split(',')
    cnt_word = 0
    for j in range(len(options)):
        now_feat = get_embedding(options[j].strip(), word_vectors, get_vector)
        if np.abs(now_feat.sum()) > 0:
            cnt_word += 1
            feat += now_feat
    if cnt_word > 0:
        feat = feat / cnt_word

    if np.abs(feat.sum()) == 0:
        return None
    else:
        # feat = feat / (np.linalg.norm(feat) + 1e-6)
        return feat 
Example 6
Project: luscan-devel   Author: blackye   File: wordnet_app.py    License: GNU General Public License v2.0 6 votes vote down vote up
def get_static_welcome_message():
    """
    Get the static welcome page.
    """
    return \
"""
<h3>Search Help</h3>
<ul><li>The display below the line is an example of the output the browser
shows you when you enter a search word. The search word was <b>green</b>.</li>
<li>The search result shows for different parts of speech the <b>synsets</b>
i.e. different meanings for the word.</li>
<li>All underlined texts are hypertext links. There are two types of links:
word links and others. Clicking a word link carries out a search for the word
in the Wordnet database.</li>
<li>Clicking a link of the other type opens a display section of data attached
to that link. Clicking that link a second time closes the section again.</li>
<li>Clicking <u>S:</u> opens a section showing the relations for that synset.</li>
<li>Clicking on a relation name opens a section that displays the associated
synsets.</li>
<li>Type a search word in the <b>Next Word</b> field and start the search by the
<b>Enter/Return</b> key or click the <b>Search</b> button.</li>
</ul>
""" 
Example 7
Project: nball4tree   Author: gnodisnait   File: util_file.py    License: MIT License 6 votes vote down vote up
def create_parent_children_file(ln, ofile="/Users/tdong/data/glove_wordSenseChildren.txt",
                                w2vile= "/Users/tdong/data/glove/glove.6B.50d.txt"):
    """
    the problem of this method is: a->b->c, but b is not in the w2v file, a and c are in the w2v.
    the relation between a->c is brocken
    :param ln:
    :param ofile:
    :param w2vile:
    :return:
    """
    lst = ln.split()
    lines = [" ".join(["*root*"] + lst + ["\n"])]
    with open(w2vile, 'r') as vfh:
        vocLst = [word.split()[0] for word in vfh.readlines()]
    while lst:
        parent = lst.pop(0)
        children = [ele.name() for ele in wn.synset(parent).hyponyms() if ele.name().split('.')[0] in vocLst]
        newLine = " ".join([parent] + children + ["\n"])
        lines.append(newLine)
        print(parent, "::", children)
        lst += children
    with open(ofile, 'w') as ofh:
        ofh.write("".join(lines)) 
Example 8
Project: nball4tree   Author: gnodisnait   File: util_file.py    License: MIT License 6 votes vote down vote up
def clean_wordsense_path(ifile="", w2vFile ="", ofile=""):
    lines = []
    with open(w2vFile, 'r') as ifh:
        vocLst = [ele.split()[0] for ele in ifh.readlines()]
    with open(ifile, 'r') as ifh:
        for ln in ifh:
            wlst = ln.strip().split()
            if len(wlst) > 2:
                node = wlst[0]
                lsts = [[ele.name() for ele in lst if ele.name().split(".")[0] in vocLst]
                        for lst in wn.synset(node).hypernym_paths()]
                wspath = sorted(lsts, key = len)[-1]
                lines.append(" ".join(wlst[:2] + wspath+["\n"]))
            else:
                lines.append(ln)
    with open(ofile, 'w') as ofh:
        ofh.write("".join(lines)) 
Example 9
def get_static_welcome_message():
    """
    Get the static welcome page.
    """
    return """
<h3>Search Help</h3>
<ul><li>The display below the line is an example of the output the browser
shows you when you enter a search word. The search word was <b>green</b>.</li>
<li>The search result shows for different parts of speech the <b>synsets</b>
i.e. different meanings for the word.</li>
<li>All underlined texts are hypertext links. There are two types of links:
word links and others. Clicking a word link carries out a search for the word
in the Wordnet database.</li>
<li>Clicking a link of the other type opens a display section of data attached
to that link. Clicking that link a second time closes the section again.</li>
<li>Clicking <u>S:</u> opens a section showing the relations for that synset.</li>
<li>Clicking on a relation name opens a section that displays the associated
synsets.</li>
<li>Type a search word in the <b>Next Word</b> field and start the search by the
<b>Enter/Return</b> key or click the <b>Search</b> button.</li>
</ul>
""" 
Example 10
def senti_synset(self, *vals):
        from nltk.corpus import wordnet as wn

        if tuple(vals) in self._db:
            pos_score, neg_score = self._db[tuple(vals)]
            pos, offset = vals
            if pos == 's':
                pos = 'a'
            synset = wn.synset_from_pos_and_offset(pos, offset)
            return SentiSynset(pos_score, neg_score, synset)
        else:
            synset = wn.synset(vals[0])
            pos = synset.pos()
            if pos == 's':
                pos = 'a'
            offset = synset.offset()
            if (pos, offset) in self._db:
                pos_score, neg_score = self._db[(pos, offset)]
                return SentiSynset(pos_score, neg_score, synset)
            else:
                return None 
Example 11
Project: razzy-spinner   Author: rafasashi   File: wordnet_app.py    License: GNU General Public License v3.0 5 votes vote down vote up
def lemma_property(word, synset, func):

    def flattern(l):
        if l == []:
            return []
        else:
            return l[0] + flattern(l[1:])

    return flattern([func(l) for l in synset.lemmas if l.name == word]) 
Example 12
Project: razzy-spinner   Author: rafasashi   File: wordnet_app.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _get_synset(synset_key):
    """
    The synset key is the unique name of the synset, this can be
    retrived via synset.name()
    """
    return wn.synset(synset_key) 
Example 13
Project: razzy-spinner   Author: rafasashi   File: wordnet_app.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _collect_one_synset(word, synset, synset_relations):
    '''
    Returns the HTML string for one synset or word

    :param word: the current word
    :type word: str
    :param synset: a synset
    :type synset: synset
    :param synset_relations: information about which synset relations
    to display.
    :type synset_relations: dict(synset_key, set(relation_id))
    :return: The HTML string built for this synset
    :rtype: str
    '''
    if isinstance(synset, tuple): # It's a word
        raise NotImplementedError("word not supported by _collect_one_synset")

    typ = 'S'
    pos_tuple = _pos_match((synset.pos(), None, None))
    assert pos_tuple is not None, "pos_tuple is null: synset.pos(): %s" % synset.pos()
    descr = pos_tuple[2]
    ref = copy.deepcopy(Reference(word, synset_relations))
    ref.toggle_synset(synset)
    synset_label = typ + ";"
    if synset.name() in synset_relations:
        synset_label = _bold(synset_label)
    s = '<li>%s (%s) ' % (make_lookup_link(ref, synset_label), descr)
    def format_lemma(w):
        w = w.replace('_', ' ')
        if w.lower() == word:
            return _bold(w)
        else:
            ref = Reference(w)
            return make_lookup_link(ref, w)

    s += ', '.join(format_lemma(l.name()) for l in synset.lemmas())

    gl = " (%s) <i>%s</i> " % \
        (synset.definition(),
         "; ".join("\"%s\"" % e for e in synset.examples()))
    return s + gl + _synset_relations(word, synset, synset_relations) + '</li>\n' 
Example 14
Project: razzy-spinner   Author: rafasashi   File: wordnet_app.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _collect_all_synsets(word, pos, synset_relations=dict()):
    """
    Return a HTML unordered list of synsets for the given word and
    part of speech.
    """
    return '<ul>%s\n</ul>\n' % \
        ''.join((_collect_one_synset(word, synset, synset_relations)
                 for synset
                 in wn.synsets(word, pos))) 
Example 15
Project: razzy-spinner   Author: rafasashi   File: wordnet_app.py    License: GNU General Public License v3.0 5 votes vote down vote up
def toggle_synset_relation(self, synset, relation):
        """
        Toggle the display of the relations for the given synset and
        relation type.

        This function will throw a KeyError if the synset is currently
        not being displayed.
        """
        if relation in self.synset_relations[synset.name()]:
            self.synset_relations[synset.name()].remove(relation)
        else:
            self.synset_relations[synset.name()].add(relation)

        return self 
Example 16
Project: razzy-spinner   Author: rafasashi   File: wordnet_app.py    License: GNU General Public License v3.0 5 votes vote down vote up
def toggle_synset(self, synset):
        """
        Toggle displaying of the relation types for the given synset
        """
        if synset.name() in self.synset_relations:
            del self.synset_relations[synset.name()]
        else:
            self.synset_relations[synset.name()] = set()

        return self 
Example 17
Project: razzy-spinner   Author: rafasashi   File: sentiwordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def all_senti_synsets(self):
        from nltk.corpus import wordnet as wn
        for key, fields in self._db.items():
            pos, offset = key
            pos_score, neg_score = fields
            synset = wn._synset_from_pos_and_offset(pos, offset)
            yield SentiSynset(pos_score, neg_score, synset) 
Example 18
Project: razzy-spinner   Author: rafasashi   File: sentiwordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, pos_score, neg_score, synset):
        self._pos_score = pos_score
        self._neg_score = neg_score
        self._obj_score = 1.0 - (self._pos_score + self._neg_score)
        self.synset = synset 
Example 19
Project: razzy-spinner   Author: rafasashi   File: sentiwordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __str__(self):
        """Prints just the Pos/Neg scores for now."""
        s = "<"
        s += self.synset.name() + ": "
        s += "PosScore=%s " % self._pos_score
        s += "NegScore=%s" % self._neg_score
        s += ">"
        return s 
Example 20
Project: razzy-spinner   Author: rafasashi   File: sentiwordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __repr__(self):
        return "Senti" + repr(self.synset) 
Example 21
Project: jingwei   Author: li-xirong   File: wordnet_similarity.py    License: MIT License 5 votes vote down vote up
def wup_similarity(tagx, tagy):
    scores = []
    for pos in [wn.NOUN, wn.VERB, wn.ADJ, wn.ADJ_SAT, wn.ADV]:
        try:
            synsetx = wn.synset('%s.%s.01' % (tagx,pos))
            synsety = wn.synset('%s.%s.01' % (tagy,pos))
            score = synsetx.wup_similarity(synsety)
            if score is None:
                score = 0
        except Exception, e:
            score = 0
        scores.append(score) 
Example 22
Project: crawl-dataset   Author: e-lab   File: getIdFromWord.py    License: ISC License 5 votes vote down vote up
def getId(name):
    ids = []
    try:
        ss = wn.synset(str(name)+'.n.01')
        wordid = ss.pos()+str(ss.offset())
        print(wordid)
        ids.append(wordid)
    except:
        print(name+' failed')
    return ids 
Example 23
Project: sklearn-theano   Author: sklearn-theano   File: overfeat_wordnet_hierarchy.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_all_leafs(synset_name):
    hitem = hierarchy.get(synset_name, None)
    if hitem is None:
        raise Exception('synset is not in hierarchy')

    if hitem['children']:
        leafs = []
        for csynset in hitem['children']:
            leafs = leafs + get_all_leafs(csynset)
        leafs = list(np.unique(leafs))
        return leafs
    else:
        return [synset_name] 
Example 24
Project: Context-aware-ZSR   Author: ruotianluo   File: convert_gcn.py    License: MIT License 5 votes vote down vote up
def getnode(x):
    return wn.synset(x) 
Example 25
Project: Context-aware-ZSR   Author: ruotianluo   File: convert_sync.py    License: MIT License 5 votes vote down vote up
def getnode(x):
    return wn.synset(x) 
Example 26
Project: luscan-devel   Author: blackye   File: wordnet_app.py    License: GNU General Public License v2.0 5 votes vote down vote up
def lemma_property(word, synset, func):

    def flattern(l):
        if l == []:
            return []
        else:
            return l[0] + flattern(l[1:])

    return flattern([func(l) for l in synset.lemmas if l.name == word]) 
Example 27
Project: luscan-devel   Author: blackye   File: wordnet_app.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _get_synset(synset_key):
    """
    The synset key is the unique name of the synset, this can be
    retrived via synset.name
    """
    return wn.synset(synset_key) 
Example 28
Project: luscan-devel   Author: blackye   File: wordnet_app.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _collect_one_synset(word, synset, synset_relations):
    '''
    Returns the HTML string for one synset or word

    :param word: the current word
    :type word: str
    :param synset: a synset
    :type synset: synset
    :param synset_relations: information about which synset relations
    to display.
    :type synset_relations: dict(synset_key, set(relation_id))
    :return: The HTML string built for this synset
    :rtype: str
    '''
    if isinstance(synset, tuple): # It's a word
        raise NotImplementedError("word not supported by _collect_one_synset")

    typ = 'S'
    pos_tuple = _pos_match((synset.pos, None, None))
    assert pos_tuple is not None, "pos_tuple is null: synset.pos: %s" % synset.pos
    descr = pos_tuple[2]
    ref = copy.deepcopy(Reference(word, synset_relations))
    ref.toggle_synset(synset)
    synset_label = typ + ";"
    if synset.name in synset_relations.keys():
        synset_label = _bold(synset_label)
    s = '<li>%s (%s) ' % (make_lookup_link(ref, synset_label), descr)
    def format_lemma(w):
        w = w.replace('_', ' ')
        if w.lower() == word:
            return _bold(w)
        else:
            ref = Reference(w)
            return make_lookup_link(ref, w)

    s += ', '.join([format_lemma(l.name) for l in synset.lemmas])

    gl = " (%s) <i>%s</i> " % \
        (synset.definition,
         "; ".join(["\"%s\"" % e for e in synset.examples]))
    return s + gl + _synset_relations(word, synset, synset_relations) + '</li>\n' 
Example 29
Project: luscan-devel   Author: blackye   File: wordnet_app.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _collect_all_synsets(word, pos, synset_relations=dict()):
    """
    Return a HTML unordered list of synsets for the given word and
    part of speech.
    """
    return '<ul>%s\n</ul>\n' % \
        ''.join((_collect_one_synset(word, synset, synset_relations)
                 for synset
                 in wn.synsets(word, pos))) 
Example 30
Project: luscan-devel   Author: blackye   File: wordnet_app.py    License: GNU General Public License v2.0 5 votes vote down vote up
def toggle_synset_relation(self, synset, relation):
        """
        Toggle the display of the relations for the given synset and
        relation type.

        This function will throw a KeyError if the synset is currently
        not being displayed.
        """
        if relation in self.synset_relations[synset.name]:
            self.synset_relations[synset.name].remove(relation)
        else:
            self.synset_relations[synset.name].add(relation)

        return self