[英]Python question about dictionary(debugging)
我知道這是一個相對基本的問題。 我試圖根據給定的字典驗證給定的兩個句子是否是同義詞。 例如,如果字典是 [(movie, film), (john, jack)] 那么“john likes movie”和“jack likes film”是同義詞,因此下面的函數將返回 true。 我使用lower/strip/split將兩個字符串中的每一個都更改為單詞列表,然后我嘗試使用for和if條件比較兩個列表。 我想不通我哪里做錯了。
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']
當你的“電影”不是一個鍵,而是一個值。
{'電影':'電影','revadfsdfs':'廣告'}
.. ^....... ^ ...... ^ ...... ^
鍵 ..... 值 .... 鍵 .... 值
在我看來,真正的問題是,您的方法不正確。 因為字典是一種單向信息,所以當你想檢查'電影'到'電影'和'電影'到'電影'時,不要使用字典。
看起來您正在嘗試為您想要實現的目標做一些不必要的復雜事情。
a.lower()
b.lower()
a.strip()
b.strip()
對實際程序沒有任何作用
您命名變量的方式也很難閱讀,所以也許可以選擇一個合適的名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.