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

Python中LDA调用fetch_20newsgroups遇403错误及参数疑问

解决20newsgroups数据集403错误及手动加载方案

403 Forbidden错误原因

scikit-learn的fetch_20newsgroups默认数据源服务器现在限制了直接请求,Colab的公共IP大概率被服务器拦截,导致自动下载失败。

手动下载及对应原参数的处理步骤

1. 手动获取全量数据集

在Colab中执行以下命令直接下载并解压完整的20newsgroups数据集(对应原代码subset='all'的全量数据):

!wget https://ndownloader.figshare.com/files/5975967
!unzip 5975967 -d 20newsgroups

2. 实现原代码的remove参数逻辑

原代码的remove=('headers','footers','quotes')是剔除邮件的头部信息、尾部签名和引用内容,用scikit-learn自带的工具函数就能实现同样效果:
先导入处理函数:

from sklearn.datasets.twenty_newsgroups import (
    strip_newsgroup_headers,
    strip_newsgroup_footers,
    strip_newsgroup_quotes
)

再定义统一处理函数:

def clean_doc(doc):
    doc = strip_newsgroup_headers(doc)
    doc = strip_newsgroup_footers(doc)
    doc = strip_newsgroup_quotes(doc)
    return doc.strip()

3. 加载并处理成原代码['data']的格式

遍历解压后的文件夹,读取所有文档并执行清理,最终得到和原代码输出一致的文档列表:

import os

docs = []
data_root = "./20newsgroups/20news-bydate-all"
# 遍历所有分类文件夹
for category in os.listdir(data_root):
    category_dir = os.path.join(data_root, category)
    if not os.path.isdir(category_dir):
        continue
    # 遍历分类下的所有文档
    for filename in os.listdir(category_dir):
        file_path = os.path.join(category_dir, filename)
        with open(file_path, 'r', encoding='latin1') as f:
            raw_content = f.read()
            cleaned_content = clean_doc(raw_content)
            if cleaned_content:  # 跳过清理后为空的文档
                docs.append(cleaned_content)

此时的docs变量完全等价于原代码fetch_20newsgroups(...)['data']的输出。

验证处理效果

随机抽取文档查看清理结果:

import random
print(random.choice(docs))

内容的提问来源于stack exchange,提问作者Partha Shankar Nayak

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 21:52:35