【发布时间】:2023-03-19 14:47:01
【问题描述】:
我正在尝试使用带有 python 的 JSON 评论来计算平均情绪极性。但是,我的代码要么无限循环以获取所有极性,要么使用 avg = sum(blob.polarity) / len(blob.polarity) 得到错误“浮动对象不可迭代”
JSON 评论数据是一个字典列表,例如:
[
{
"date": "xx/xx/xxxx",
"rate": "8.0",
"Review text": "its such an awesome movie! the actions are intense!"
},
...
]
我的代码:
response = requests.get("https://imdb.com/reviews/ironman.json") #not an actual URL
if response:
data = json.loads(response.text)
content = ""
for line in data:
review = line["Review text"]
content = content + review + " "
blob = textblob.TextBlob(content)
print("The average review polarity:", blob.polarity)
else:
print("404 error.")
输出:
The average review polarity: 0.21027251552795012
The average review polarity: 0.20845378442639165
The average review polarity: 0.20358391721811314
……………… looping forever...
我正在尝试获取所有评论的平均极性。基本上,我只需要得到一个极性输出,它是平均值而不是多个。我试着做sum(blob.polarity) / len(blob.polarity), 这样做会给我一个错误。我被卡住了。
【问题讨论】:
-
if response.ok不是if response -
请展示你尝试做 `sum(blob.polarity) / len(blob.polarity)` 以便我们向你展示如何正确地做(因为这是计算平均值的正确方法)。您的代码中也没有任何内容可以使其永远循环。
-
@martineau - 我刚刚在 blob = textblob 下面添加了 avg = float(sum/blob.polarity) / float(len(blob.polarity)。然后 print("平均评论极性:",avg )
-
试试调试器。您会惊讶于使用这个基本工具可以学到什么。
-
@TomServo - 如果我的教授教我们如何在 colab 上使用该工具,那就太好了,我在任何地方都看不到它。
标签: python json sentiment-analysis