如何解决从字符串中匹配字典中的“键”,并返回“值”
尊敬的堆栈溢出社区:
我一直在尝试解决以下情况:用户输入一个输入,它是一个字符串,并将字符串中的单词与预定义词典中的“键”进行比较,以查看是否存在匹配项。如果存在匹配项,则为字典中的“键”返回相应的“值”。
例如:
thisdict = { “ limit”:“通过网上银行进行的每日交易限额”, “ payout”:“通过网上银行的支付贷款”, }
print('Notes:',end ='') user_input = input()
假设用户在提示符下输入以下输入: 客户希望增加购买限额
我当时正在考虑通过对输入应用'.split()'来解决这个问题,以便每个单词都可以隔离。
然后,运行“ for循环”以将字符串中的每个单词与字典中的每个键进行匹配。随后,返回与字符串中的单词匹配的“键”的任何“值”。
因此,在示例中,输入 client想增加他们的购买限额,它将匹配单词'limit'并通过网上银行返回每日交易限额
我一直很难将其转换为Python代码,并希望获得一些帮助。
解决方法
您可以使用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))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。