【问题标题】:Calculating sentiment polarity using IMDb JSON reviews使用 IMDb JSON 评论计算情绪极性
【发布时间】: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


【解决方案1】:

我认为你应该多做一些类似的事情:

response = requests.get("https://imdb.com/reviews/ironman.json")
if response.ok:
   reviews = json.loads(response.text)
   content = ' '.join([review["Review text"] for review in reviews])
   blob = textblob.TextBlob(content)
   print("The average review polarity:", blob.polarity)

else:
   print("404 error.")

我看不到在每次评论文本连接后计算极性的意义

【讨论】:

  • 您好 DevLounge,这太棒了!但是,我们需要计算所有评论的平均值。感谢您的帮助,谢谢!
猜你喜欢
  • 2018-12-15
  • 2019-10-06
  • 2016-08-12
  • 2014-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-02
  • 1970-01-01
相关资源
最近更新 更多