Search code examples
pythoncsvsentiment-analysistextblob

Sentiment analysis on a csv file using textblob


I used sentiment analysis on a CSV file and the output prints the polarity and subjectivity of a sentence. How can I get the output in a table format along with the classification of the sentence as positive or negative or neutral added to it?

    import csv
    from textblob import TextBlob

    infile = 'sentence.csv'

    with open(infile, 'r') as csvfile:
        rows = csv.reader(csvfile)
    for row in rows:
        sentence = row[0]
        blob = TextBlob(sentence)
        print (sentence)
        print (blob.sentiment.polarity, blob.sentiment.subjectivity)

the output for my code is :

    i am very happy
    1.0 1.0
    its very sad
    -0.65 1.0
    they are bad
    -0.6999999999999998 0.6666666666666666
    hate the life
    -0.8 0.9
    she is so fantastic
    0.4 0.9

Thanks in advance.


Solution

  • I would recommend creating a list of lists and importing that into a pandas dataframe to get a table structure

    import csv
    from textblob import TextBlob
    import pandas as pd
    import numpy as np
    
    infile = 'sentence.csv'
    bloblist = list()
    
    with open(infile, 'r') as csvfile:
        rows = csv.reader(csvfile)
    
    for row in rows:
        sentence = row[0]
        blob = TextBlob(sentence)
        bloblist.append((sentence,blob.sentiment.polarity, blob.sentiment.subjectivity))
    

    This will give you a list of lists called bloblist Convert it into a pandas dataframe like

    df = pd.DataFrame(bloblist, columns = ['sentence','sentiment','polarity'])
    

    After adding that you can create custom calculations like this:

    df['positive'] = np.where(df.sentiment > .5,1,0)