【发布时间】:2017-08-30 16:32:35
【问题描述】:
我有两个从 wordnet.synsets() 生成的同义词列表:
import numpy as np
import nltk
from nltk.corpus import wordnet as wn
import pandas as pd
#convert tag to the one used by wordnet
def convert_tag(tag):
tag_dict = {'N': 'n', 'J': 'a', 'R': 'r', 'V': 'v'}
try:
return tag_dict[tag[0]]
except KeyError:
return None
#define a function to find synset reference
def doc_to_synsets(doc):
token = nltk.word_tokenize(doc)
tag = nltk.pos_tag(token)
wordnet_tag = convert_tag(tag)
syns = [wn.synsets(token, wordnet_tag) for token in nltk.word_tokenize(doc)]
syns_list = [token[0] for token in syns if token]
return syns_list
#convert two example text documents
doc1 = 'This is a test function.'
doc2 = 'Use this function to check if the code in doc_to_synsets is correct!'
s1 = doc_to_synsets(doc1)
s2 = doc_to_synsets(doc2)
我正在尝试编写一个函数来查找 s2 中的同义词集,该同义词集对于 s1 中的每个同义词集具有最大的“路径相似性”分数。因此,对于包含 4 个独特的同义词集的 s1,该函数应返回 4 个路径相似度分数,我会将其转换为 pandas Series 对象以便于计算。
到目前为止,我一直在编写以下代码
def similarity_score(s1, s2):
list = []
for word1 in s1:
best = max(wn.path_similarity(word1, word2) for word2 in s2)
list.append(best)
return list
但是,它只返回一个没有任何值的空列表。
[]
有人愿意看看我的 for 循环有什么问题,或许可以在这个问题上启发我吗?
谢谢。
【问题讨论】:
-
请在单个代码 sn-p 中创建一个minimal reproducible example,我们可以立即复制、粘贴和运行,包括函数调用和打印。
标签: python nltk list-comprehension wordnet synonym