您的位置首页 >人工智能 >

解决 ImportError No module named 'torchtext',根据 torch 版本挑选适配 torchtext 版本

遇到 ImportError: No module named 'torchtext' 报错,大多是两种情况,要么环境里根本没装 torchtext,要么装的 torchtext 和当前 torch 版本不匹配,正确做法是先查询本机 torch 版本,对照版本对照表,安装对应兼容的 torchtext,就能解决这个导入报错。很多新手直接执行 pip install torchtext,默认装最新版,但是 torchtext 已经停止迭代,最高稳定版本是 0.18.0,高版本 PyTorch 没有配套 torchtext,装上之后要么找不到模块,要么后续运行报版本冲突;处理流程是先进入 Python 环境打印 torch 版本,查表找到匹配的 torchtext 版本,使用 pip 指定版本安装,优先新建虚拟环境,避免其他包互相干扰;如果项目允许,也可以改用 torchdata、Hugging Face Datasets 替代已经停更的 torchtext。

torch 与 torchtext 兼容对照表

torch 版本配套 torchtext 版本
torch 2.3.0torchtext 0.18.0
torch 2.2.0torchtext 0.17.0
torch 2.1.0torchtext 0.16.0
torch 2.0.0torchtext 0.15.0
torch 1.13.0torchtext 0.14.0
torch 1.12.0torchtext 0.13.0

排查 & 安装步骤清单

  1. 查看当前 torch 版本,在 python 交互窗口执行:

import torch

print(torch.__version__)

  1. 对照上面表格,找到对应的 torchtext 版本号
  2. 指定版本安装示例,以 torch2.2.0 为例:

pip install torchtext==0.17.0

  1. 安装完成后重新导入测试:import torchtext
  2. 依旧报错:建议新建 conda/venv 虚拟环境,重装 torch + 配套 torchtext

补充提示

  • torchtext 已于 2024 年 4 月停止开发,0.18.0 是最后一个稳定版本,高于 2.3.0 的 PyTorch 官方不再提供适配 torchtextPyTorch
  • 不要直接 pip install torchtext,容易自动安装不兼容版本
  • 老项目代码如果依赖 torchtext 旧 API,升级版本后会出现函数找不到的问题

【相关 FAQ】

问题 1:ImportError: No module named 'torchtext',是不是只要随便装 torchtext 就可以?

回答 1:ImportError: No module named 'torchtext' 不能随便安装 torchtext,必须按照 torch 版本挑选兼容 torchtext,版本不匹配依然会报错或者运行异常。

问题 2:torch 版本太高,找不到兼容的 torchtext 怎么办?

回答 2:torch 版本太高没有兼容的 torchtext,有两个方案,要么降级 torch 到 2.3.0 及以内,安装 0.18.0 版本 torchtext;要么改造代码,抛弃 torchtext,换成 Hugging Face Datasets、torchdata。

问题 3:安装完对应版本 torchtext 之后还是报 No module named 'torchtext'?

回答 3:安装完对应版本 torchtext 依旧报错,大概率是多环境冲突,当前运行的 python 解释器和 pip 安装包的环境不一致,建议新建虚拟环境,统一安装 torch 和配套 torchtext。

问题 4:torchtext 为什么没有新版本,新版本 torch 不再适配 torchtext 吗?

回答 4:torchtext 已经停止维护,0.18.0 是最终稳定版,高于 2.3.0 的 torch 没有官方适配 torchtext,所以遇到 ImportError: No module named 'torchtext' 优先核对 torch 版本再选 torchtext。

【参考资料】

[2026-11-09](torchtext 版本兼容说明,PyPI torchtext 主页)PyPI

[2026-11-09](TorchText 官方文档:停止开发公告)PyTorch 官网

[2026-11-09](ImportError: No module named 'torchtext' 版本匹配问题)PyTorch 论坛

【免责声明】

本内容仅为 ImportError: No module named 'torchtext' 报错的版本匹配方案,torch、torchtext 版本兼容关系由 PyTorch 官方定义;不同操作系统、CUDA 版本、Python 版本会额外影响包安装效果;torchtext 已经停止维护,长期新项目不推荐继续依赖 torchtext,本文不构成项目开发选型强制建议。