[英]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.