python - 从python中的json文件中查找字符串匹配
问题描述
{
"appconfig": {
"username" : "test",
"password" : "testpassowrd"
},
"bot": [
{
"contains": [],
"exact": ["hi","hy","hey","hlw"],
"response": "hey there"
},
{
"contains": [],
"exact": ["gm","good morning","vgm"],
"response": "good morning"
}
],
"blocked": [],
}
我将 json 片段存储在子文件中并在执行期间打开文件:
with open('/data.json', 'r') as f:
data = json.load(f)
我期待在python中将字符串与JSON中的精确数组一一匹配。使用 lambda 过滤器的最佳方法是什么?
例如
user_msg = 'hi'
如果存在值,我必须在每个精确数组中一一匹配发送响应。
提前致谢。
编辑:1
解决方案
通过迭代每个可能的数据集,您可以像这样每次运行检查:
def getResponse(user_msg):
for data_set in data["bot"]:
if user_msg in data_set["exact"]:
return data_set["response"]
getResponse(user_msg)
这假设数据已经定义并且在全局范围内,而下一个函数在内部读取文件:
def getResponse(user_msg):
with open('/data.json', 'r') as f:
data = json.load(f)
for data_set in data["bot"]:
if user_msg in data_set["exact"]:
return data_set["response"]
getResponse(user_msg)
推荐阅读
- python - 为什么我的队列挂着异步事件循环
- java - 在java中使用其他类的变量
- aws-lambda - 对于 AWS Cloudwatch 中的 Lambda,overProvisioned Memory 意味着什么?
- java - 如何在 android studio java 中使用 OkHttpClient 发布多个图像?
- r - R基于双字符分隔符分割字符串
- python - 在 Python numpy 中计算两个二维数组的不同非零值
- java - 如何将具有数组的 JSON 转换为 Java 对象
- google-sheets - 如何在 google 表格中编写宏以刷新 bigquery 数据连接器?
- c++ - inotify 是一次性解决方案吗
- magento - whatsapp 分享链接 url 甚至没有显示描述和缩略图 magento 1.9