首页 > 解决方案 > 从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

在此处输入图像描述

标签: pythonjsonpython-3.x

解决方案


通过迭代每个可能的数据集,您可以像这样每次运行检查:

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)

推荐阅读