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

Python中如何基于标签关键词为评论测试数据生成标记变量?

在Python中生成评论标签的0/1标记变量的实现方案

当然可以实现!你可以借助Pandas的字符串处理功能,结合简单的文本预处理,轻松为每条评论生成对应标签的0/1标记。下面是具体的步骤和代码示例:

1. 准备工作与文本预处理

首先导入必要的库,并对评论文本做标准化处理(转小写、去除标点),确保关键词匹配的准确性:

import pandas as pd
import re
from string import punctuation

# 文本预处理函数:统一转小写+移除标点符号
def preprocess_text(text):
    text = text.lower()
    text = text.translate(str.maketrans('', '', punctuation))
    return text

# 假设你的测试数据集comment_test包含评论内容列Comment_Text
comment_test['Processed_Comment'] = comment_test['Comment_Text'].apply(preprocess_text)

2. 方法一:自定义函数精准匹配(支持短语关键词)

如果你的标签包含多词短语(比如"your company"),这种方法能确保完整短语匹配:

# 定义检查标签是否存在的函数
def check_tag_presence(comment, keywords):
    # 对关键词做同样的预处理
    processed_keywords = [kw.lower().translate(str.maketrans('', '', punctuation)) for kw in keywords]
    # 遍历关键词,只要有一个匹配就返回1,否则返回0
    for kw in processed_keywords:
        if kw in comment:
            return 1
    return 0

# 假设你的标签数据集tags_df包含Tag_Name(标签名)和Keywords(关键词列表)列
# 示例标签数据:
tags_df = pd.DataFrame({
    'Tag_Name': ['Brand Reputation'],
    'Keywords': [['brand', 'brands', 'reputation', 'your company']]
})

# 为每个标签生成对应的0/1标记列
for _, tag_row in tags_df.iterrows():
    tag_name = tag_row['Tag_Name']
    keywords = tag_row['Keywords']
    comment_test[tag_name] = comment_test['Processed_Comment'].apply(lambda x: check_tag_presence(x, keywords))

3. 方法二:使用Pandas str.contains快速批量匹配

如果追求代码简洁性,可以用正则表达式结合str.contains实现快速批量处理:

# 遍历每个标签生成正则匹配模式
for _, tag_row in tags_df.iterrows():
    tag_name = tag_row['Tag_Name']
    keywords = tag_row['Keywords']
    # 生成正则模式:用|分隔所有关键词,同时转义特殊字符避免匹配异常
    pattern = '|'.join([re.escape(kw.lower()) for kw in keywords])
    # 将匹配结果转为0/1整数
    comment_test[tag_name] = comment_test['Processed_Comment'].str.contains(pattern).astype(int)

进阶优化:匹配完整单词

如果不想出现类似"branded"被误判为匹配"brand"的情况,可以给正则加上单词边界限制:

pattern = '|'.join([r'\b' + re.escape(kw.lower()) + r'\b' for kw in keywords])

处理完成后,comment_test数据集会新增每个标签对应的列,值为1表示该评论包含对应标签的关键词,0则表示不包含。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:06:13