首页 > 解决方案 > 使用 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()

标签: pythonnlpundefined

解决方案


一定是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]}')

推荐阅读