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

使用TextBlob时出现HTTP Error 400的原因及解决方法

TextBlob detect_language() HTTP 400错误原因及解决方法

问题重现

运行以下代码时出现HTTP 400错误:

from textblob import TextBlob

text1 = TextBlob('I looked for Mary and Samantha at the bus station')
a = text1.detect_language()
print(a)

错误信息:

639 class HTTPDefaultErrorHandler(BaseHandler):
    640     def http_error_default(self, req, fp, code, msg, hdrs):
--> 641         raise HTTPError(req.full_url, code, msg, hdrs, fp)
    642 
    643 class HTTPRedirectHandler(BaseHandler):

HTTPError: HTTP Error 400: Bad Request

错误原因

TextBlob默认使用Google的公开语言检测API实现detect_language()功能,但该API已停止免费公开服务,且接口协议发生变更,导致发送的请求不符合当前API要求,从而返回400 Bad Request错误。

解决方法

方法1:使用TextBlob本地检测模块(无需联网)

TextBlob内置了基于Pattern库的本地语言检测器,无需调用外部API:

  1. 若未下载过TextBlob语料库,先执行:
python -m textblob.download_corpora
  1. 修改代码指定使用PatternDetector:
from textblob import TextBlob
from textblob.detect import PatternDetector

text1 = TextBlob('I looked for Mary and Samantha at the bus station', detector=PatternDetector())
a = text1.detect_language()
print(a)  # 输出: en

方法2:替换为第三方本地语言检测库

使用langdetect库,基于N-gram模型实现本地语言检测,无联网依赖:

  1. 安装库:
pip install langdetect
  1. 示例代码:
from langdetect import detect

text1 = 'I looked for Mary and Samantha at the bus station'
a = detect(text1)
print(a)  # 输出: en

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 22:37:43