微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

努力创建字典来存储 IBM Watson Entity Analysis 的结果

如何解决努力创建字典来存储 IBM Watson Entity Analysis 的结果

我正在努力在字典中捕获 IBM Watson 实体分析的结果。我想通过一个函数提取每个链接的情绪。我创建了一个函数提取单个 url。但是试图存储结果的字典只捕获最后一个 url 结果。我是 Python 新手,感谢您的帮助。

这是我的实体分析代码

# function to process an URL
def processurl(url_to_analyze):
  # end point
  endpoint = f"{URL}/v1/analyze"

  # credentials
  username = "apikey"
  password = API_KEY

  # parameters
  parameters = {
      
      "version": "2020-08-01"
      
  }

  # headers
  headers = {
      "Content-Type":"application/json"
  }

  # watson options
  watson_options = {
      "url": url_to_analyze,"features": {
          "entities": {
              "sentiment": True,"emotion": True,"limit":10
          }
      }

  }

  # return
  response = requests.post(endpoint,data=json.dumps(watson_options),headers=headers,params=parameters,auth=(username,password)
                           )
  return response.json()

这是我创建的用于传递上面结果的函数

# create a function to extract the entities from the result data
def getentitylist(data,threshold):
  result = []
  for entity in data["entities"]:
    relevance = float(entity["relevance"])
    if relevance > threshold:
      result.append(entity["text"])
  return result

遍历 URL 后,我似乎无法将结果存储在字典中,以便我可以将其传递给我的函数获取实体结果

# method II: loop through news api urls and perform entity analysis and store it in a dictionary
entitydict = {}
for url in url_to_analyze:
  entitydict.update(processurl(url))

解决方法

我看不到您在何处调用 getentitylist,但在您的 url 循环中

entitydict = {}
for url in url_to_analyze:
  entitydict.update(processurl(url))

update 将根据键值更新字典。 IE。这将覆盖字典中已有的任何键的值。您的回复将类似于:

{
  "usage": {
    "text_units": 1,"text_characters": 2708,"features": 1
  },"retrieved_url": "http://www.cnn.com/","language": "en","entities": [
    {
      "type": "Company","text": "CNN","sentiment": {
        "score": 0.0,"label": "neutral"
      },"relevance": 0.784947,"disambiguation": {
        "subtype": [
          "Broadcast","AwardWinner","RadioNetwork","TVNetwork"
        ],"name": "CNN","dbpedia_resource": "http://dbpedia.org/resource/CNN"
      },"count": 9
    }
  ]
}

将更新的键位于顶级,即。 usageretrieved_urlretrieved_urlentities。因此 entitydict 将只包含最后一个 url 的响应,因为这些键的先前值将被覆盖。

您应该做的是使用 url 作为每个响应的键。

entitydict = {}
for url in url_to_analyze:
  entitydict.update({url : processurl(url)})

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?