mardi 22 décembre 2020

Running code based on condition in string using ifelse

I'd like to run python code to get the subjectivity score from each row of the text of my data frame using if-else function. I have eng, kor, jap, Chinese texts and would like to run the code based on its language. If it is not English, I will translate it to English and run the analysis for the score. I'd like to store these scores in a new column named "subjectivity".

My code is attached below but it does not give any result, even the column. Could anyone find mistakes in my code?

from textblob import TextBlob
import pandas as pd
from googletrans import Translator
import operator

try:
    if operator.contains(df["lang"], "en"):
        df["subjectivity"] = df["text"].apply(getSubjectivity)
    elif operator.contains(df["lang"], "ko"):
        engString = translator.translate(df["text"],src='ko')
        engString = engString.text
        df["subjectivity"] = engString.apply(getSubjectivity)
    elif operator.contains(df["lang"], "ja"):
       engString = translator.translate(df["text"],src='ja')
       engString = engString.text
       df["subjectivity"] = engString.apply(getSubjectivity)
    else:
        engString = translator.translate(df["text"],src='zh-cn')
        engString = engString.text
        df["subjectivity"] = engString.apply(getSubjectivity)
except:
    df["lang"] = None

Aucun commentaire:

Enregistrer un commentaire