从字符串中匹配字典中的“键”,并返回“值”

时间:2020-08-14 01:28:43

标签: python string dictionary matching

尊敬的堆栈溢出社区:

我一直在尝试解决以下情况:用户输入一个输入,它是一个字符串,并将字符串中的单词与预定义词典中的“键”进行比较,以查看是否存在匹配项。如果存在匹配项,则为字典中的“键”返回相应的“值”。

例如:

thisdict = { “ limit”:“通过网上银行进行的每日交易限额”, “ payout”:“通过网上银行的支付贷款”, }

print('Notes:',end ='') user_input = input()

假设用户在提示符下输入以下输入: 客户希望增加购买限额

我当时正在考虑通过对输入应用'.split()'来解决这个问题,以便每个单词都可以隔离。

然后,运行“ for循环”以将字符串中的每个单词与字典中的每个键进行匹配。随后,返回与字符串中的单词匹配的“键”的任何“值”。

因此,在示例中,输入 client想增加他们的购买限额,它将匹配单词'limit'并通过网上银行返回每日交易限额

我一直很难将其转换为Python代码,并希望获得一些帮助。

1 个答案:

答案 0 :(得分:1)

您可以使用in来测试单词是否是字典中的键:

def lookup(dct, sentence):
    """
    splits the input sentence into words and returns the value from dct for
    the first word that is a key, or None if none are found.
    """
    for word in sentence.split():
        if word in dct:  # <== this tests the word against the dictionary keys
            return dct[word]  # <== do the lookup (we know the key exists)
    return None  # <== no matches were found in the 'for' loop


thisdict = { "limit": "daily transaction limits through online banking", "payout": "payout loan through online banking", }

print('Notes: ', end='')
user_input = input()

print(lookup(thisdict, user_input))