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

NLP任务中无法从utils导入process_tweet和build_freqs,求排查错误

问题根源

你通过pip install utils安装的是一个通用第三方工具库,里面根本没有process_tweet和build_freqs这两个函数。这俩是自定义的NLP工具函数,几乎都是Coursera NLP专项课(比如吴恩达团队的课程)或者入门教程里的配套代码,不属于公开PyPI仓库里的包。

解决步骤
  • 先卸载错装的utils包(避免后续导入混淆):
    pip uninstall utils
    
  • 获取正确的utils.py文件:
    • 如果你是跟着某个课程/教程学习的,直接去课程的GitHub仓库、配套资料里下载那个名为utils.py的本地文件(注意是和你的项目脚本同目录的文件,不是PyPI包)。
    • 要是找不到配套文件,你也可以自己实现这两个核心功能,下面是最常用的实现版本:
      import re
      import string
      from nltk.corpus import stopwords
      from nltk.stem import PorterStemmer
      from nltk.tokenize import TweetTokenizer
      
      def process_tweet(tweet):
          """清洗推文:分词、去停用词、词干提取等"""
          stemmer = PorterStemmer()
          stopwords_en = stopwords.words('english')
          # 移除@用户提及
          tweet = re.sub(r'@[A-Za-z0-9_]+', '', tweet)
          # 移除URL链接
          tweet = re.sub(r'https?://[A-Za-z0-9./]+', '', tweet)
          # 移除#标签符号,保留标签文本
          tweet = re.sub(r'#', '', tweet)
          # 用推文专用分词器处理
          tokenizer = TweetTokenizer(preserve_case=False, strip_handles=True, reduce_len=True)
          tokens = tokenizer.tokenize(tweet)
          # 过滤停用词和标点,提取词干
          cleaned_tokens = []
          for token in tokens:
              if token not in stopwords_en and token not in string.punctuation:
                  cleaned_tokens.append(stemmer.stem(token))
          return cleaned_tokens
      
      def build_freqs(tweets, labels):
          """构建(词, 标签)的频率字典,用于后续NLP任务"""
          freq_dict = {}
          for label, tweet in zip(labels, tweets):
              for word in process_tweet(tweet):
                  key = (word, label)
                  freq_dict[key] = freq_dict.get(key, 0) + 1
          return freq_dict
      
  • 正确导入函数:
    • 把上面的代码保存为utils.py,放在你的Python项目根目录(和你的主脚本同一个文件夹)。
    • 然后在你的主脚本里这样导入:
      from utils import process_tweet, build_freqs
      
补充说明

如果是跟着特定课程学习,尽量用课程配套的utils.py,因为不同教程的函数实现可能有细微差异(比如处理特殊字符的规则),但核心功能都是清洗文本和统计词频。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:56:17