使用googletrans

问题描述

所以我想使用Textblob情感来计算我的数据的情感。但是,在计算情感之前,我将数据从印尼语转换为英语。

这是我的密码

import pandas as pd
df = pd.read_csv('file.csv',encoding="utf-16")
from googletrans import Translator
translator = Translator()
df['english'] = df['Comment'].apply(translator.translate,src='id',dest='en')
#print(df)
#print(df['english'])
from textblob import TextBlob
def sentiment_calc(text):
    try:
        return TextBlob(text).sentiment
    except:
        return None
    
df['sentiment']=df['english'].apply(lambda text: TextBlob(text).sentiment)
print(df['sentiment'])

但是后来我得到了这个错误

TypeError: The `text` argument passed to `__init__(text)` must be a string,not <class 'googletrans.models.Translated'>

解决方案吗?顺便说一下,翻译结果很好。

解决方法

发生错误是因为您给TextBlob提供了字符串以外的其他内容。
df['english']的类型为<class 'googletrans.models.Translated'>,因此必须将其更改为字符串。

import pandas as pd
df = pd.read_csv('file.csv',encoding="utf-8")
from googletrans import Translator
translator = Translator()
df['english'] = df['Comment'].apply(translator.translate,src='id',dest='en')
#print(df)
#print(df['english'])
from textblob import TextBlob
def sentiment_calc(text):
    try:
        return TextBlob(text).sentiment
    except:
        return None
df['english'] = df['english'].astype(str) #change type to string 
df['sentiment']=df['english'].apply(lambda text: TextBlob(text).sentiment)
print(df['sentiment'])

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...