For循环总是在python中打印最后一次迭代

2024-05-29 11:06:44 发布

您现在位置:Python中文网/ 问答频道 /正文

for sentence in reviewlist:
    print(sentence)
    scores = sid.polarity_scores(sentence)
    for key in sorted(scores):
         print('{0}: {1}, '.format(key, scores[key]), end='')

这段代码打印句子的所有迭代,但分数只打印最后一次迭代。请帮忙


Tags: key代码informatfor分数sentence句子
1条回答
网友
1楼 · 发布于 2024-05-29 11:06:44

给定要打印的end=''参数,除了在print(sentence)之外,您永远不会打印换行符,因此您应该期望您以前的分数和当前的句子打印在同一行上

我建议尝试一些调试,看看您得到了什么值:

for sentence in reviewlist:
    scores = sid.polarity_scores(sentence)
    print(sentence, scores)  # make sure that scores isn't empty
    for key in sorted(scores):
         print('{0}: {1}, '.format(key, scores[key]), end='')
    print()  # actually get a newline between sentences

如果scores作为空字典返回,那么这可能就是问题所在。如果这没有帮助,请更新您的问题,提供有关您的输入和sid函数返回的分数值的更多详细信息

相关问题 更多 >

    热门问题