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

NLTK调用stopwords报错:function对象无words属性

报错原因

这是典型的命名覆盖冲突问题:
你先通过from nltk.corpus import stopwords导入了NLTK提供的停用词模块,此时stopwords变量名指向的是NLTK的corpus子模块。但你紧接着定义了同名函数def stopwords(text):,Python中后定义的同名变量/函数会覆盖之前的引用,此时全局命名空间里的stopwords已经变成了你自定义的过滤函数。
当函数内部执行stopwords.words('english')时,解释器找到的stopwords是你定义的函数对象本身,函数没有words这个属性,自然就抛出AttributeError: 'function' object has no attribute 'words'错误。

解决方法

两种方案二选一即可,推荐第一种,语义更清晰:

  • 方案1:重命名自定义过滤函数,避免和导入的模块重名
    from nltk.corpus import stopwords
    import nltk
    # 首次使用没下载过语料就先执行这行
    # nltk.download('stopwords')
    
    # 函数名改成非冲突的名称,比如remove_stopwords
    def remove_stopwords(text):
        """a function for removing the stopword"""
        sw = stopwords.words('english')
        text = [word.lower() for word in text.split() if word.lower() not in sw]
        return " ".join(text)
    
    # 调用时对应修改函数名即可
    df['col_text'] = df['col_text'].apply(remove_stopwords)
    
  • 方案2:导入NLTK停用词模块时起别名,从导入层避免冲突
    # 导入时给NLTK的stopwords起别名
    from nltk.corpus import stopwords as nltk_sw
    import nltk
    # 首次使用没下载过语料就先执行这行
    # nltk.download('stopwords')
    
    # 自定义函数名可以保留
    def stopwords(text):
        """a function for removing the stopword"""
        # 用别名调用NLTK的停用词接口
        sw = nltk_sw.words('english')
        text = [word.lower() for word in text.split() if word.lower() not in sw]
        return " ".join(text)
    
    # 原有apply调用逻辑不需要修改
    df['col_text'] = df['col_text'].apply(stopwords)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 12:54:27