python - 使用 python 运行我的 nlp 脚本时,如何解决“名称'score'未定义”的问题?
问题描述
运行我的脚本时,我得到了以下反馈,
1 回溯(最后一次调用):文件“testcore.py”,第 20 行,在 print(f'\tScore: {score[0]}, Value: {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 循环范围。您score
在 for 循环内部定义并尝试在 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]}')
推荐阅读
- nginx - 如何在 Nginx 上配置具有相同 URL 的多个站点
- reactjs - 将事件处理程序放在 NextJS _document 中——以及 NextJS 页面和 React SPA 之间的关系
- apache-flink - 如何在 Apache Flink 中创建外部目录表
- c++ - CUDA: Fill matrix with results of summation
- java - 获取用户输入,然后使用 AWT 打印新文本
- javascript - How to fix get request and response with whole html
- symfony - 定义“nelmio_cors”不支持配置键“defaults”
- c# - WPF 组合框似乎导致 InvalidCastException
- mysql - SQL日期间隔不适用于AND子句
- c# - 如果 int 值等于 x 替换为字符串