0

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.

3
  • are you familiar with pandas dataframes? Commented Jan 16, 2018 at 18:11
  • I am a beginner but i can understand it Commented Jan 16, 2018 at 18:43
  • @Usernamenotfound I tried it using pandas but i am not able to do it for a csv file. i am able to do it for individual sentences. Thank you Commented Jan 16, 2018 at 18:44

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

sure will do it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.