[英]How do I solve the problem of “name 'score' is not defined” when running my nlp script using python?
運行腳本時,我收到以下反饋,
1個回溯(最近一次通話):文件“ testcore.py”,第20行,在打印中(f'\\ tScore:{score [0]},值:{score [1]}')NameError:name'score'沒有定義
完全相同的腳本可以在另一台計算機上完美運行,我只是不明白有什么問題。
這是我的代碼:
from pycorenlp import StanfordCoreNLP
nlp = StanfordCoreNLP('http://localhost:9000')
fhand=open('airbnbuk.txt', encoding='utf-8')
count=0
for sentence in fhand:
print(sentence)
count=count+1
print(count)
result = nlp.annotate(sentence,
properties={
'annotators': 'sentiment',
'outputFormat': 'json',
'timeout': '5000'
})
for s in result['sentences']:
score = (s['sentimentValue'], s['sentiment'])
print(f'\tScore: {score[0]}, Value: {score[1]}')
nlp.close()
必須是 python
版本不匹配。格式字符串是在 Python 3.6
中引入的。您可能正在運行錯誤消息的較低版本。
好的,最好查看已編輯/格式化的問題。 因此,這樣做的原因是for循環作用域。 您可以在for循環內定義score
,然后嘗試在for循環范圍之外訪問它。
如果您更改代碼以包括分數的默認值,或者檢查分數是否存在,則代碼將起作用:
for sentence in fhand:
...
score = None
for s in result['sentences']:
score = (s['sentimentValue'], s['sentiment'])
if score is not None:
print(f'\tScore: {score[0]}, Value: {score[1]}')
要么
for sentence in fhand:
...
score = (0, 0) # some default tuple
for s in result['sentences']:
score = (s['sentimentValue'], s['sentiment'])
print(f'\tScore: {score[0]}, Value: {score[1]}')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.