我正在尝试逐行分析文本文件中每个给定句子的情绪。每当我使用链接的第一个问题的硬编码句子时,代码就会起作用。当我使用文本文件输入时,我得到TypeError
.
这与这里提出的问题有关。文本文件代码中的一行一行来自这个问题:
第一个有效,第二个使用文本文件("I love you. I hate him. You are nice. He is dumb")
不起作用。这是代码:
from pycorenlp import StanfordCoreNLP
nlp = StanfordCoreNLP('http://localhost:9000')
results = []
with open("c:/nlp/test.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"]))
我收到此错误:
第 21 行,在
s["索引"],
类型错误:列表索引必须是整数或切片,而不是 str
我没有安装Stanfort-lib,所以我无法使用它的系统进行测试。 但是方式,它返回的是,您的结果变量是"字典列表"类型或某种嵌套类型
反正我做了一个测试
results = []
with open("tester.txt","r") as f:
for line in f.read().split('n'):
print("Line:" + line)
sentences = [
{
"index":1,
"word":line,
"sentimentValue": "sentVal",
"sentiment":"senti"
}
]
results.append(sentences)
然后我构建您的循环并对其进行一些调整以满足我的需求,例如:
for res in results:
for s in res:
print("%d: '%s': %s %s" % (
s["index"],
" ".join(s["word"]),
s["sentimentValue"], s["sentiment"]))
是什么印了我以下内容
1: 'I l o v e y o u .': sentVal senti
1: 'I h a t e h i m .': sentVal senti
1: 'Y o u a r e n i c e .': sentVal senti
1: 'H e i s d u m b': sentVal senti
所以基本上代码有效。 但是你必须弄清楚返回值是什么类型,在它从那个斯坦福 API 返回 - 例如>"类型(结果)">
获得此信息后,可以从遍历值的循环开始,如果您不知道嵌套值的类型,则可以调用 Anotehr Print of Type。 一直向下,直到到达包含要使用的项目的图层
最后要指出的一件事。在您链接的说明中,在注释中。 在那里,他告知如何将文本传递到 API 中。在那里,他解释说API摆脱了切片和格式化,您只能发送整个文本。 如果您没有得到任何结果,请记住这一点
看起来我解决了这个问题。正如 londo 指出的:这一行将S
设置为List
,但它应该是dict
的,就像在原始代码中一样:
s = res["sentences"]
我将代码移动到同一循环中,在该循环中逐行读取和分析文件,并直接在那里打印结果。所以新代码看起来像这样:
from pycorenlp import StanfordCoreNLP
nlp = StanfordCoreNLP('http://localhost:9000')
with open("c:/nlp/test.txt","r") as f:
for line in f.read().split('n'):
res = nlp.annotate(line,
properties={
'annotators': 'sentiment',
'outputFormat': 'json',
'timeout': 15000,
})
for s in res["sentences"]:
print("%d: '%s': %s %s" % (
s["index"],
" ".join([t["word"] for t in s["tokens"]]),
s["sentimentValue"], s["sentiment"]))
结果看起来符合预期,没有任何错误消息:
0: 'I love you .': 3 Positive
0: 'I hate him .': 1 Negative
0: 'You are nice .': 3 Positive
0: 'He is dumb .': 1 Negative