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

Python开发Twitch机器人:CSV分类词汇与聊天消息对比实现问询

基于CSV的黑名单匹配实现

首先明确你的CSV结构,假设是第一行存分类名,后续每行对应各分类下的词汇/短语:

辱骂类,广告类,低俗类
傻逼,代刷等级,黄段子
垃圾,免费领皮肤,低俗内容

实现步骤

  1. 读取CSV到内存
    用编程语言把CSV转成「分类名-词汇列表」的字典结构,以Python为例:
import csv

blacklist = {}
with open('blacklist.csv', 'r', encoding='utf-8') as f:
    reader = csv.reader(f)
    categories = next(reader)  # 提取第一行的分类名
    for row in reader:
        for idx, word in enumerate(row):
            if word.strip():  # 跳过空内容
                category = categories[idx]
                if category not in blacklist:
                    blacklist[category] = []
                blacklist[category].append(word.strip())
  1. 加载用户选定的分类
    根据用户频道设置,把启用的分类词汇合并成待匹配列表:
enabled_categories = ['辱骂类', '广告类']
target_words = []
for cat in enabled_categories:
    if cat in blacklist:
        target_words.extend(blacklist[cat])
  1. 聊天消息比对逻辑
    对每条收到的消息做匹配,支持模糊匹配或全词匹配:
  • 模糊匹配(只要消息包含词汇就触发):
def check_message(message):
    msg_lower = message.lower()
    for word in target_words:
        if word.lower() in msg_lower:
            return True  # 触发封禁/删消息
    return False
  • 全词匹配(避免误判,比如只匹配完整的「傻逼」而非「傻逼逼」):
import re

def check_message_full_match(message):
    msg_lower = message.lower()
    for word in target_words:
        pattern = re.compile(r'\b' + re.escape(word.lower()) + r'\b')
        if pattern.search(msg_lower):
            return True
    return False

INI文件的可行性分析

完全可行,而且INI的「节-属性」结构天生适配分类管理,比CSV更直观,维护成本更低。

假设INI结构:

[辱骂类]
words = 傻逼,垃圾,智障

[广告类]
words = 代刷等级,免费领皮肤,加群领福利

[低俗类]
words = 黄段子,低俗内容

实现步骤

  1. 读取INI到内存
    以Python的configparser模块为例:
from configparser import ConfigParser

config = ConfigParser()
config.read('blacklist.ini', encoding='utf-8')

blacklist = {}
for section in config.sections():
    words = config.get(section, 'words').split(',')
    blacklist[section] = [word.strip() for word in words if word.strip()]
  1. 分类加载与消息比对
    这部分逻辑和CSV方案完全一致,因为最终都得到「分类名-词汇列表」的字典结构。

两种方案对比
  • CSV:适合需要用Excel等表格工具编辑的场景,但如果词汇或分类名包含逗号,需要手动转义,容易出错。
  • INI:结构清晰,天然支持分类,无需处理特殊字符转义,更适合配置类场景。

内容的提问来源于stack exchange,提问作者Fem-Tec

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 23:45:36