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

Python中检测Pandas列语言并添加语言代码列报错求助

问题分析

你的代码存在以下几个问题:

  • 未调用TextBlob的detect_language()方法,直接将TextBlob对象赋值给DataFrame列,导致类型不匹配错误
  • 循环中每次赋值都会覆盖整个lang列,最终只会保留最后一条文本的检测结果
  • 缺少pandas和TextBlob的导入语句
  • 首次使用TextBlob需要下载语言检测模型
解决步骤与修正代码
  1. 先安装依赖包:
pip install pandas textblob
  1. 下载TextBlob语言检测模型(仅需执行一次):
from textblob import TextBlob
TextBlob.download_corpora()
  1. 修正后的检测代码:
import pandas as pd
from textblob import TextBlob

data = {'text':  ["It is a good option","Better to have this way","es un portal informático para geeks","は、ギーク向けのコンピューターサイエンスポータルです"]}
df = pd.DataFrame(data)

# 批量处理文本列,生成对应语言代码列
df['lang'] = df['text'].apply(lambda text: TextBlob(text).detect_language())

# 查看结果
print(df)

运行后会得到包含语言代码的DataFrame,结果示例:

text lang
0                                It is a good option   en
1                            Better to have this way   en
2                  es un portal informático para geeks   es
3  は、ギーク向けのコンピューターサイエンスポータルです   ja

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 06:20:22