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

如何为gensim.corpora.textcorpus.TextCorpus配置自定义停用词列表

你修改全局STOPWORDS不生效的原因是:Gensim 4.0的TextCorpus类在模块加载阶段就已经把默认停用词读取存入了类属性stopwords中,你后续修改gensim.parsing.preprocessing.STOPWORDS不会同步更新TextCorpus已经缓存的类属性,因此子类TextDirectoryCorpus默认还是用旧的停用词表。

不需要自定义子类,两种更简便的实现方式如下:


方案1:实例化时传入自定义停用词(仅对当前实例生效)

直接在创建TextDirectoryCorpus实例时,通过stopwords参数传入你的自定义停用词集合即可:

import os
import gensim

# 自定义停用词
custom_stopwords = frozenset({'aber', 'alle', 'allem', 'allen' })

# 准备测试文件
os.makedirs('test123', exist_ok=True)
with open('test123/test.txt', 'w') as fout:
    fout.write('aber alle lachten \n allen gefallen \n')

# 实例化时传入stopwords参数
corpus = gensim.corpora.textcorpus.TextDirectoryCorpus(
    'test123',
    stopwords=custom_stopwords
)

for text in corpus.get_texts():
    print(text)
# 输出符合预期:['lachten', 'gefallen']

方案2:修改TextCorpus类属性(全局生效,所有子类默认使用新停用词)

如果你希望所有TextCorpus的子类在实例化时都默认使用你的自定义停用词,直接修改TextCorpus的类属性即可:

import gensim

custom_stopwords = frozenset({'aber', 'alle', 'allem', 'allen' })
# 全局修改TextCorpus的默认停用词
gensim.corpora.textcorpus.TextCorpus.stopwords = custom_stopwords

# 后续所有TextCorpus子类实例化不传stopwords都会用自定义列表
corpus = gensim.corpora.textcorpus.TextDirectoryCorpus('test123')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 18:06:05