[英]Why do I get a TypeError when importing a textfile line by line for sentiment analysis instead of using a sentence hard-coded?
我試圖逐行分析文本文件中每個給定句子的情感。 每當我使用鏈接的第一個問題的硬編碼語句時,代碼就可以正常工作。 使用文本文件輸入時,出現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 [“ index”],
TypeError:列表索引必須是整數或切片,而不是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
因此,代碼基本上可以正常工作。 但是您必須弄清楚返回值是什么類型,例如,在從那個Stanfort API中獲取返回值之后->“ type(results)”
當獲得此信息時,可以從遍歷值的循環開始,如果您不知道嵌套值是什么類型,則可以調用type的anotehr打印。 一直向下直到到達要處理的項目所在的層
最后要指出的一件事。 在鏈接的說明中,在“注釋”中。 他在那里提供了有關如何將文本傳遞到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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.