目录
问题描述:
想要得到一个英文句子的同义句。可以通过从wordnet中查找同义词,替换对应的单词,从而得到完整的同义句。
问题解决:
wordnet安装:
首先需要先安装好wordnet,安装步骤如下:
首先安装nltk包--> 安装好之后,输入python命令,执行 import nltk --> 再安装wordnet, 执行命令nltk.download('wordnet')-->安装成功即可。
得到同义句的方式有两种:
方式一:
思想:
从wordnet中获取当前句子中每一个单词对应同义词列表中的随机一个单词,作为该单词的同义词。从而得到该句子对应的同义句。
代码实现:
# 随机返回同义词中的一个,作为同义词。
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)
方式二:
思想:
从wordnet中获取当前句子中每一个单词对应同义词列表中,与当前单词相似度最高的单词作为该单词的同义词,从而得到完整的同义句。
代码实现:
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)