python - 从字符串中匹配字典中的“键”,并返回“值”
问题描述
亲爱的堆栈溢出社区:
我一直在尝试解决用户输入一个字符串的情况,然后将字符串中的单词与预定义字典中的“键”进行比较,以查看是否匹配。如果匹配退出,则为字典中的“键”返回相应的“值”。
例如:
thisdict = { "limit": "网上银行每日交易限额", "payout": "网上银行支付贷款", }
print('注:', end='') user_input = input()
假设用户在提示中输入以下内容: 客户想增加他们的购买限额
我正在考虑通过将“.split()”应用于输入来解决它,这样每个单词都会被隔离。
然后,运行“for 循环”以将字符串中的每个单词与字典中的每个键匹配。随后,返回与字符串中的单词匹配的“键”的任何“值”。
因此,在输入客户想增加购买限额的示例中,它会匹配“限额”一词并通过网上银行返回每日交易限额。
我在将其转换为 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))
推荐阅读
- javascript - 如何在 JavaScript 中 (a) 从 32 位整数中提取和 (b) 删除位
- php - Analytics 在新的 Web+App 中跟踪自定义事件
- html - 如何使用 HTML 将边框应用于电子邮件模板
- c++ - 这是部分模板专业化吗?
- angular - 在具有角度材料的表格列标题上显示复选框
- javascript - 使用 Angular 6 插入数据时更新数据表
- azure - 带有布尔值的 SCIM 问题的 Azure 用户/组预配
- angular - 如何在选定的列表项上添加 CSS 类
- javascript - 目前业界最常用的发送 HTTP 请求的方式是什么(AJAX、Fetch API、Async/Await)?
- javascript - 如何通过淘汰赛实现 CSS 星级评分