How to iterate through each line of a text file and get the sentiment of those lines using python?

2024/11/18 12:29:30

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 the following code : from pycorenlp import StanfordCoreNLP

nlp = StanfordCoreNLP('http://localhost:9000')
res = nlp.annotate("I love you. I hate him. You are nice. He is dumb",properties={'annotators': 'sentiment','outputFormat': 'json','timeout': 1000,})
for s in res["sentences"]:print("%d: '%s': %s %s" % (s["index"]," ".join([t["word"] for t in s["tokens"]]),s["sentimentValue"], s["sentiment"]))

But, my requirement is, I have a text file which contains around 100 sentences which are seperated by new line .

So, I tried using the following code to open a text file and read the sentences and find the sentiment for each sentence.

from pycorenlp import StanfordCoreNLPnlp = StanfordCoreNLP('http://localhost:9000')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,})
for s in res["sentences"]:print("%d: '%s': %s %s" % (s["index"]," ".join([t["word"] for t in s["tokens"]]),s["sentimentValue"], s["sentiment"]))

But, somehow all the sentences of the text file are overridden and I'm getting the sentiment for the last sentence. As, I'm new to python can anyone please help me out regarding the same...

Answer

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 StanfordCoreNLPnlp = 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.

https://en.xdnf.cn/q/120076.html

Related Q&A

RECURSIVE function that will sum digits of input

Trying to write a piece of code that will sum the digits of a number. Also I should add that I want the program to keep summing the digits until the sum is only 1 digit. For example, if you start with …

Make sure matrix row took from text file are same length(python3) [duplicate]

This question already has answers here:Making sure length of matrix row is all the same (python3)(3 answers)Closed 10 years ago.so I have this code to input a matrix from a text file:import ospath = in…

how to randomize order of questions in a quiz in python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 9 years ago.Improve…

How transform days to hours, minutes and seconds in Python

I have value 1 day, 14:44:00 which I would like transform into this: 38:44:00. Ive tried the following code: myTime = ((myTime.days*24+myTime.hours), myTime.minutes, myTime.seconds) But it doesnt work.…

Brute Force in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 10 years ago.Improv…

Choosing only non-zeros from a long list of numbers in text file

I have a text file with a long list of numbers. I would like to choose only the non-zeros and make another text file. This is a portion of the input file:0.00000E+00 0.00000E+00 0.00000E+00 0.00000…

Why can I not plot using Python on repl.it

For practical reasons, I want to test a small piece of Pyton code on repl.it (webbased, so I do not need to install Python).The codeimport numpy as np import matplotlib.pyplot as plttime = np.array([0,…

Pull Data from web link to Dataframe [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 5…

Python program that rolls a fair die counts the number of rolls before a 6 shows up

import randomsample_size = int(input("Enter the number of times you want me to roll the die: "))if (sample_size <=0):print("Please enter a positive number!")else:counter1 = 0coun…

How to read CSV file in Python? [duplicate]

This question already has answers here:How do I read and write CSV files?(9 answers)Closed 1 year ago.Im using Spyder for Python 2.7 on Windows 8. Im trying to open and read a csv file and see all the…