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

如何在Bash中移除文本文件中存在于另一文件的词汇

移除文本文件中的停用词解决方案

嘿,我刚好处理过类似的需求,给你两个实用的方案,不管你用Python还是命令行工具都能轻松搞定!

方案1:Python 实现(最通用易改)

这个方法适合大多数人,哪怕你只有基础编程知识也能跟着改。核心思路是先把停用词加载成查询效率高的集合,再逐行处理文本过滤掉停用词:

def remove_stopwords(input_file, stopwords_file, output_file):
    # 加载停用词到集合(集合的查询速度比列表快很多)
    with open(stopwords_file, 'r') as f:
        # 如果你的停用词是每行一个,用下面这行;如果是逗号分隔,把split()换成split(',')
        stopwords = set(word.strip().lower() for word in f if word.strip())
    
    # 处理目标文本并保存结果
    with open(input_file, 'r') as in_f, open(output_file, 'w') as out_f:
        for line in in_f:
            # 按空格拆分单词,如果你需要处理标点(比如单词带逗号/句号),可以用正则优化
            words = line.strip().split()
            # 过滤停用词,保留原单词大小写(要统一小写的话,可以把word改成word.lower())
            filtered_words = [word for word in words if word.lower() not in stopwords]
            # 重新拼接成行写入结果文件
            out_f.write(' '.join(filtered_words) + '\n')

# 替换成你自己的文件路径就行
remove_stopwords("你的文本文件.txt", "停用词文件.txt", "过滤后的结果.txt")

小提示:

  • 如果你的停用词文件是逗号分隔的(比如一行里全是用逗号隔开的单词),把加载停用词的那行改成:
    stopwords = set(word.strip().lower() for word in f.read().split(',') if word.strip())
    
  • 要是需要处理标点(比如hello,这种带逗号的单词),可以用正则来拆分,先导入re模块,然后把拆分单词的代码换成:
    words = re.findall(r'\b\w+\b', line)
    
    不过这样会丢失原文本的标点和格式,按需调整就行。

方案2:Bash 脚本(适合Linux/macOS用户)

如果你不想写Python,用系统自带的命令行工具也能搞定,这里用awk来实现精准的单词过滤:

awk -v stopwords="停用词文件.txt" '
BEGIN {
    # 先把停用词加载到数组里
    while ((getline line < stopwords) > 0) {
        stopword[tolower(line)] = 1
    }
    close(stopwords)
}
{
    # 遍历每行的每个单词
    for (i=1; i<=NF; i++) {
        # 转成小写方便匹配,同时去掉单词里的标点(可选操作)
        clean_word = tolower($i)
        gsub(/[^a-zA-Z0-9]/, "", clean_word)
        # 如果不是停用词就保留
        if (!stopword[clean_word]) {
            printf "%s ", $i
        }
    }
    # 每行结束换行
    printf "\n"
}
' 你的文本文件.txt > 过滤后的结果.txt

这个脚本会逐行读取文本,逐个检查单词是否在停用词列表里,最后把过滤后的内容写入新文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:37:12