Search code examples
pythonpandasgoogle-translatetextblob

Textblob sentiment error after using googletrans


so I want to use Textblob sentiment to calculate the sentiment of my data. But, before calculating the sentiment, I translated the data from Indonesian to English.

Here are my codes

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'])

But then I got this error

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

Any Solution? By the way, the translation results were fine.


Solution

  • An error occurs because you are giving something other than a string to TextBlob.
    df['english'] type is <class 'googletrans.models.Translated'>, so it must be changed to a string.

    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'])