目前,我正在研究情感分析部分。为此,我更喜欢使用python使用Standford Core NLP库。我可以使用以下代码获得每个句子的情绪:来自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"]))
但是,我的要求是,我有一个文本文件,其中包含大约100个由新行分隔的句子。
因此,我尝试使用以下代码打开文本文件并阅读句子并找到每个句子的情绪。
from pycorenlp import StanfordCoreNLP
nlp = 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"]))
但是,不知何故,文本文件的所有句子都被覆盖了,我得到了最后一句话的情绪。因为,我是python的新手,任何人都可以帮我解决同样的事情......
我会给它一个刺,但正如我评论的那样,我不是真的合格,这段代码将是未经测试的。添加或更改的行标有# <<<<<<
。
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"]))
我认为for line in f.read().split('\n'):
可能会被更简单的for line in f:
所取代,但我不能确定没有看到你的输入文件。