How to use wordnet dictionary to get synonyms of English sentences

Table of contents

Problem Description:

problem solved:

wordnet installation:

method one:

Thought:

Code:

Method 2:

Thought:

Code:


Problem Description:

Want to get a synonym for an English sentence. You can get a complete synonym sentence by looking up synonyms from wordnet and replacing the corresponding words.

problem solved:

wordnet installation:

First of all, you need to install wordnet first. The installation steps are as follows:

First install the nltk package --> After installation, enter the python command, execute import nltk --> then install wordnet, execute the command nltk.download('wordnet') --> the installation is successful.

There are two ways to get synonyms:

method one:

Thought:

Obtain a random word in the synonym list corresponding to each word in the current sentence from wordnet, as the synonym of the word. Thus, the corresponding synonym of the sentence is obtained.

Code:

# 随机返回同义词中的一个,作为同义词。
from nltk.corpus import wordnet
import random

def get_synonyms(word):
    synonyms = set()
    for syn in wordnet.synsets(word): # 查询给定单词的WordNet同义词集合(synset)
        for lemma in syn.lemmas(): 
            # 获取同义词集合syn中的所有词条(lemma)。一个同义词集合可以包含多个词条,每个词条代表一个具体的同义词。
            synonyms.add(lemma.name())
    return list(synonyms)

def replace_words(sentence):
    words = sentence.split()
    print("单词是:",words)
    new_sentences =  []
    for word in words:
        synonyms = get_synonyms(word)
        print("synonyms is :", synonyms)
        if synonyms:
            new_word  = random.choice(synonyms) # 随机选择同义词
            new_sentences.append(new_word)
        else:
            new_sentences.append(word)
    return ' '.join(new_sentences)

sentence = "We researched and found the best price at MacConnection . "
new_sentence = replace_words(sentence)
print(new_sentence)

Method 2:

Thought:

Obtain the synonym list corresponding to each word in the current sentence from wordnet, and use the word with the highest similarity with the current word as the synonym of the word, so as to obtain a complete synonym sentence.

Code:

def get_synonyms(sentence):
    synonyms = []
    words = sentence.split()
    for word in words:
        max_similarity = 0.0
        best_synonyms = word
        synsets = wordnet.synsets(word)
        print("synsets", synsets)
        for synset in synsets:

            for lemma in synset.lemmas():
                similarity = synset.path_similarity(lemma.synset())
                if similarity is not None and similarity > max_similarity:
                    max_similarity = similarity
                    best_synonyms = lemma.name()
        synonyms.append(best_synonyms)
    return ' '.join(synonyms)

sentence = "we are family, and i like you !"
syn_sentence = get_synonyms(sentence)
print(syn_sentence)

 

Guess you like

Origin blog.csdn.net/weixin_41862755/article/details/131435583