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

文本数据集过滤技术求助:仅保留指定词汇集中的词汇

嘿,我来帮你搞定这个文本过滤的需求!要从每行文本里只保留指定的词汇,用Python来做非常高效,尤其是用Pandas处理结构化的数据集,下面是具体的实现方案:

方案:用Python + Pandas过滤文本数据集

首先,我先把你给的指定词汇列表做了去重(原列表里有重复的evidence),然后转成集合——集合的查找速度比列表快很多,适合批量处理大量文本。接下来直接上带注释的代码,一看就懂:

import pandas as pd

# 1. 定义目标词汇集合(自动去重,查找效率拉满)
target_words = {
    'cell', 'CDKs', 'lung', 'mutations', 'monomeric', 
    'Casitas', 'Background', 'acquired', 'evidence', 
    'kinases', 'small', 'Oncogenic'
}

# 2. 加载你的数据集(假设是CSV格式,要是是txt就换成pd.read_table)
df = pd.read_csv('your_dataset.csv')

# 3. 定义核心过滤函数:处理单行文本
def filter_text(text):
    # 把文本拆成单个单词(默认按空格拆分)
    words = text.split()
    # 只保留在目标集合里的单词,还能保持原顺序
    filtered_words = [word for word in words if word in target_words]
    # 把筛选后的单词拼回成字符串
    return ' '.join(filtered_words)

# 4. 把过滤函数应用到整个Text列,生成新的筛选后列
df['Filtered_Text'] = df['Text'].apply(filter_text)

# 5. 保存处理好的数据集(按需选择保存格式)
df.to_csv('filtered_dataset.csv', index=False)

额外细节优化说明

  • 标点清理:如果你的文本里带标点(比如单词后面跟逗号、句号),可以先在过滤函数里清理标点,避免漏匹配:
    import string
    def filter_text(text):
        # 先移除所有标点符号
        text_clean = text.translate(str.maketrans('', '', string.punctuation))
        words = text_clean.split()
        filtered_words = [word for word in words if word in target_words]
        return ' '.join(filtered_words)
    
  • 大小写兼容:要是需要忽略大小写匹配(比如文本里的cdks也想匹配CDKs),可以统一转成小写后再判断:
    target_words_lower = {word.lower() for word in target_words}
    def filter_text(text):
        words = text.split()
        filtered_words = [word for word in words if word.lower() in target_words_lower]
        return ' '.join(filtered_words)
    
  • 纯文本文件处理:如果你的数据集是没有ID列的纯文本(每行一条内容),用纯Python文件操作也很简单:
    target_words = {'cell', 'CDKs', ...} # 同上定义集合
    
    with open('input.txt', 'r', encoding='utf-8') as infile, open('output.txt', 'w', encoding='utf-8') as outfile:
        for line in infile:
            words = line.strip().split()
            filtered_line = ' '.join([w for w in words if w in target_words])
            outfile.write(filtered_line + '\n')
    

拿你给的示例数据测试的话,处理后结果会是这样:

ID Text Filtered_Text
0 Cyclin-dependent kinases CDKs regulate a CDKs kinases
1 Abstract Background Non-small cell lung Background small cell lung

完全符合你的需求!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:42:58