You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python开发Telegram bot查找JSON文件所有含指定词的匹配项

问题说明

当前代码使用dict.get()方法查询字典值,该方法仅支持键名完全精确匹配,无法识别键名中包含指定关键词的模糊匹配场景,因此搜索关键词cat时,仅能返回键名完全等于cat对应的FILE3,无法获取cat flag dog、home cat两个包含关键词的键对应的FILE5、FILE10。
涉及的JSON存储结构如下:

{
    "cat": "FILE3",
    "cat flag dog": "FILE5",
    "zebra tiger": "FILE9",
    "home cat": "FILE10",
    "tv snow": "FILE12"
}

原有存在缺陷的代码:

@bot.message_handler(func=lambda message: True)
def echo_message(message):
    with open("database.json", "r") as json_file:
            File = json.load(json_file)
        res = File.get(message.text.lower(), 'word not found')
        bot.send_message(message.chat.id, message.text)
        bot.send_message(message.chat.id, 'contain in:')
        bot.send_message(message.chat.id, res)

注:原代码还存在with代码块缩进错误的语法问题,修改版本中已同步修正。

修改方案

核心实现逻辑:遍历字典所有键值对,判断用户输入的关键词是否为键名的子串,收集所有符合匹配规则的值后统一返回。
修改后可正常运行的完整代码:

import json
import telebot

# 替换为你自己的Telegram机器人Token
bot = telebot.TeleBot("YOUR_BOT_TOKEN")

@bot.message_handler(func=lambda message: True)
def echo_message(message):
    # 预处理用户输入:去前后空格、统一转小写
    keyword = message.text.strip().lower()
    
    # 加载映射文件
    with open("database.json", "r") as json_file:
        file_map = json.load(json_file)
    
    # 收集所有键名包含关键词的对应值
    match_result = [
        file_val for file_key, file_val in file_map.items()
        if keyword in file_key.lower()
    ]

    bot.send_message(message.chat.id, message.text)
    bot.send_message(message.chat.id, 'contain in:')
    # 根据匹配结果返回对应内容
    if not match_result:
        bot.send_message(message.chat.id, 'word not found')
    else:
        bot.send_message(message.chat.id, '\n'.join(match_result))

if __name__ == "__main__":
    bot.infinity_polling()
可选优化点
  • 若机器人消息量较大,可将JSON文件加载逻辑移到函数外部,服务启动时加载一次即可,无需每次收到消息都读取磁盘文件,降低IO开销
  • 可按需增加匹配规则,比如支持多关键词匹配、全词匹配等,只需要调整列表推导式中的判断条件即可
  • 可增加异常捕获逻辑,避免JSON文件格式错误、文件不存在等问题导致机器人崩溃

内容的提问来源于stack exchange,提问作者Mauro Sumino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.03 02:54:40