Skip to content Skip to sidebar Skip to footer

How To Iterate Through Each Line Of A Text File And Get The Sentiment Of Those Lines Using Python?

Currently, I'm working on Sentiment Analysis part. For this I have preferred to use Standford Core NLP library using python. I'm able to get the sentiment for each sentence using t

Solution 1:

I'll give this a stab, but as I commented, I'm not really qualified and this code will be untested. The lines added or changed are marked with # <<<<<<.

from pycorenlp import StanfordCoreNLP

nlp = StanfordCoreNLP('http://localhost:9000')

results = []     # <<<<<<

with open("/Users/abc/Desktop/test_data.txt","r") as f:
    for line in f.read().split('\n'):
        print("Line:" + line)
        res = nlp.annotate(line,
                   properties={
                       'annotators': 'sentiment',
                       'outputFormat': 'json',
                       'timeout': 1000,
                   })
        results.append(res)      # <<<<<<for res in results:              # <<<<<<
    s = res["sentences"]         # <<<<<<print("%d: '%s': %s %s" % (
        s["index"], 
        " ".join([t["word"] for t in s["tokens"]]),
        s["sentimentValue"], s["sentiment"]))

I would imagine that for line in f.read().split('\n'): could probably be replaced with the simpler for line in f:, but I can't be sure without seeing your input file.

Post a Comment for "How To Iterate Through Each Line Of A Text File And Get The Sentiment Of Those Lines Using Python?"