关于字典的Python问题(调试)
我知道这是一个相对基本的问题。我试图验证给定的两个句子是否是基于给定词典的同义词。 例如,如果字典是[(电影,电影),(约翰,杰克)],那么“约翰喜欢电影”和“杰克喜欢电影”是同义词,因此下面的函数将返回true。 我使用lower/strip/split将两个字符串中的每一个都更改为单词列表,然后尝试使用for和if条件来比较这两个列表。我不知道我哪里做错了关于字典的Python问题(调试),python,Python,我知道这是一个相对基本的问题。我试图验证给定的两个句子是否是基于给定词典的同义词。 例如,如果字典是[(电影,电影),(约翰,杰克)],那么“约翰喜欢电影”和“杰克喜欢电影”是同义词,因此下面的函数将返回true。 我使用lower/strip/split将两个字符串中的每一个都更改为单词列表,然后尝试使用for和if条件来比较这两个列表。我不知道我哪里做错了 def synonym_checker(synonyms, sentences): a=sentences[0][0]
def synonym_checker(synonyms, sentences):
a=sentences[0][0]
b=sentences[0][1]
a.lower()
b.lower()
a.strip()
b.strip()
aw=a.split()
bw=b.split()
import string
at = a.maketrans('','',string.punctuation)
bt = b.maketrans('','',string.punctuation)
ase = [w.translate(at) for w in aw]
bs = [w.translate(bt) for w in bw]
dictionary = dict(synonyms)
this = True
for i in range(0, min(len(ase), len(bs))):
if ase[i] != bs[i]:
if (bs[i] != dictionary[ase[i]]) and bs[i] not in [first for first, second in dictionary.items() if second == ase[i]]:
this = False
if (len(ase) != len(bs)):
this = False
is_synonym = this
print(ase)
print(bs)
return is_synonym # boolean
a = [("film", "movie"), ("revadfsdfs", "ads")]
b = [("I really want to watch that movie, as it had good fdf.", "I really want to watch that film, as it had good fdsaa")]
print(synonym_checker(a, b))
那么,你的错误发生在
dictionary[ase[i]]
因为你在这里所做的实际上是
{'film': 'movie', 'revadfsdfs': 'ads'}['movie']
当你的“电影”不是一个键,而是一个值
{'film':'movie','revadfsdfs':'ads'}.. ^......... ^.............. ^ ............ ^
键…值。。。。。。。钥匙价值观 在我看来,真正的问题是,你的方法不正确。因为字典是一种单向信息,所以当您想同时检查“电影”到“电影”和“电影”到“电影”时,不要使用字典 看起来你也在尝试做一些不必要的复杂的事情,以实现你的目标
a.lower()
b.lower()
a.strip()
b.strip()
对实际程序没有任何影响
您命名变量的方式也很难理解,因此可以选择一个合适的名称