使用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:
- 若未下载过TextBlob语料库,先执行:
python -m textblob.download_corpora
- 修改代码指定使用
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模型实现本地语言检测,无联网依赖:
- 安装库:
pip install langdetect
- 示例代码:
from langdetect import detect text1 = 'I looked for Mary and Samantha at the bus station' a = detect(text1) print(a) # 输出: en
内容的提问来源于stack exchange,提问作者Sara
相关产品推荐
相关产品推荐

