首页 > 解决方案 > 关于字典的Python问题(调试)

问题描述

我知道这是一个相对基本的问题。我正在尝试根据给定的字典验证给定的两个句子是否是同义词。例如,如果字典是 [(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))

标签: python

解决方案


所以,你的错误发生在

dictionary[ase[i]]

因为你在这里所做的实际上是

{'film': 'movie', 'revadfsdfs': 'ads'}['movie']

当你的“电影”不是关键,而是价值。

{'电影': '电影', 'revadfsdfs': '广告'}
.. ^....... ^................. ^ ..... ....... ^
键 ..... 值 ....... 键 ....... 值

在我看来,真正的问题是,您的方法不正确。因为字典是单向信息,所以当你想同时检查“电影”到“电影”和“电影”到“电影”时,不要使用字典。

看起来您正在尝试为您想要实现的目标做一些不必要的复杂的事情。

a.lower()
b.lower()
a.strip()
b.strip()

不对实际程序做任何事情

您命名变量的方式也很难阅读,所以也许选择一个合适的名称。


推荐阅读