【问题标题】:Find the best match in JSON file with keywords使用关键字在 JSON 文件中查找最佳匹配
【发布时间】:2017-12-12 17:28:26
【问题描述】:

我不知道如何解释,也不知道这是否可能,因为我在互联网上找不到我想要的东西。

例如,我有这个 JSON 的命令

{
    "gif": [
      "gif","show","bot"
    ],
    "doc": [
      "show","doc","bot"
    ],
    "weather": [
      "show","actual","weather"
    ]
}

用户输入此消息:

“嗨,机器人,你能告诉我实际的天气吗?”

我如何编码,我的函数将返回与用户消息中的最佳关键字匹配的命令(在这种情况下为“天气”)?

希望我的问题有点清楚

谢谢

【问题讨论】:

    标签: javascript arrays json parsing keyword


    【解决方案1】:

    您可以使用Object.keys 遍历您的JSON,然后使用array#every 使用string#includes 检查字符串中数组的每个单词是否存在。

    var keyWords = { "gif": [ "gif","show","bot" ], "doc": [ "show","doc","bot" ], "weather": [ "show","actual","weather" ] };
    var message = "Hi bot can you show me the actual weather ?";
    
    var result = Object.keys(keyWords).find(k => 
      keyWords[k].every(word => message.includes(word)));
    
    console.log(result);

    【讨论】:

    • 只是另一个问题,例如,如果我希望它与 >= 3 个关键字匹配,我该怎么办?
    • Every 会比较你的关键字中的所有单词,只有在你的字符串中找到所有单词时才会返回结果。
    • 当我运行它“unique_image_url_prefixes”时得到这个
    • @HassanImam 我希望能够找到 JSON 名称:“key” 使用关键字查找密钥....假设我想找到 bob 去鞋店购物,我想输入 Bob shoe 作为一个关键字就能找到 bob 去鞋店stackoverflow.com/questions/52196314/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    • 1970-01-01
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    相关资源
    最近更新 更多