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

如何基于规则实现Pandas字符串多关键词组的多子类别提取?

实现多组关键词的子类别匹配方案

可以通过定义分类-关键词映射字典结合自定义函数的方式实现,这种方法扩展性强,能轻松支持大量关键词组,步骤如下:

1. 定义分类映射规则

先把每个子类别对应的关键词组整理成字典,键是子类别名称,值是该类别对应的关键词列表:

category_keywords = {
    "Invoice & Payment": ["invoice", "payment"],
    "Data Request": ["data", "csv"],
    # 可直接添加更多子类别和对应关键词
    # "Other Category": ["keyword1", "keyword2"]
}

2. 编写匹配函数

写一个函数接收文本内容,遍历分类字典,检查文本是否包含对应类别的任意关键词(忽略大小写),收集所有匹配到的子类别:

def get_sub_categories(text):
    # 转小写避免大小写干扰
    text_lower = str(text).lower()
    matched_categories = []
    for category, keywords in category_keywords.items():
        # 检查是否有任意关键词出现在文本中
        if any(keyword in text_lower for keyword in keywords):
            matched_categories.append(category)
    # 用" and "连接多个匹配类别
    return " and ".join(matched_categories) if matched_categories else None

3. 应用到DataFrame

用pandas.Series.apply()方法把函数应用到Text列,生成Target Sub Category列:

import pandas as pd

# 示例数据
df = pd.DataFrame({
    "Text": ["invoice received payment sent data csv", "only data file", "payment processed"]
})

# 生成目标列
df["Target Sub Category"] = df["Text"].apply(get_sub_categories)

运行后结果示例:

TextTarget Sub Category
invoice received payment sent data csvInvoice & Payment and Data Request
only data fileData Request
payment processedInvoice & Payment

扩展说明

  • 若需要必须包含该类别的所有关键词才归类(比如同时有invoice和payment才算Invoice & Payment),把any()改成all()即可。
  • 关键词量大时,直接在category_keywords字典里新增键值对,无需修改核心逻辑。
  • 处理超大规模数据时,可把关键词组编译成正则表达式优化性能:
import re

# 编译正则,每个类别用|分隔关键词,忽略大小写
category_regex = {
    cat: re.compile('|'.join(keys), flags=re.IGNORECASE) 
    for cat, keys in category_keywords.items()
}

def get_sub_categories_regex(text):
    matched = []
    for cat, regex in category_regex.items():
        if regex.search(str(text)):
            matched.append(cat)
    return " and ".join(matched) if matched else None

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 03:12:53