如何将谷歌云自然语言实体情感响应转换为 Python 中的 JSON/dict?

Reg*_*sor 1 python serialization json google-cloud-language

我正在尝试使用谷歌云自然语言 API 来分析实体情绪。

from google.cloud import language_v1
import os 
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'path/to/json'

client = language_v1.LanguageServiceClient()
text_content = 'Grapes are good. Bananas are bad.'

# Available types: PLAIN_TEXT, HTML
type_ = language_v1.Document.Type.PLAIN_TEXT

# Optional. If not specified, the language is automatically detected.
# For list of supported languages:
# https://cloud.google.com/natural-language/docs/languages
document = language_v1.Document(content=text_content, type_=language_v1.Document.Type.PLAIN_TEXT)

# Available values: NONE, UTF8, UTF16, UTF32
encoding_type = language_v1.EncodingType.UTF8
response = client.analyze_entity_sentiment(request = {'document': document, 'encoding_type': encoding_type})
Run Code Online (Sandbox Code Playgroud)

然后我从响应中打印出实体及其属性。

for entity in response.entities:
    print('=' * 20)
    print(type(entity))
    print(entity)

====================
<class 'google.cloud.language_v1.types.language_service.Entity'>
name: "Grapes"
type_: OTHER
salience: 0.8335162997245789
mentions {
  text {
    content: "Grapes"
  }
  type_: COMMON
  sentiment {
    magnitude: 0.8999999761581421
    score: 0.8999999761581421
  }
}
sentiment {
  magnitude: 0.8999999761581421
  score: 0.8999999761581421
}

====================
<class 'google.cloud.language_v1.types.language_service.Entity'>
name: "Bananas"
type_: OTHER
salience: 0.16648370027542114
mentions {
  text {
    content: "Bananas"
    begin_offset: 17
  }
  type_: COMMON
  sentiment {
    magnitude: 0.8999999761581421
    score: -0.8999999761581421
  }
}
sentiment {
  magnitude: 0.8999999761581421
  score: -0.8999999761581421
}
Run Code Online (Sandbox Code Playgroud)

现在我想以 JSON 或字典格式存储整个响应,以便我可以将其存储到数据库中的表中或进行处理。我尝试将 Google Cloud NLP API 实体情感输出转换为 JSON以及如何通过 JSON 序列化来自谷歌自然语言 API 的对象?(没有 __dict__ 属性)但它不起作用。

如果我使用

from google.protobuf.json_format import MessageToDict, MessageToJson 
result_dict = MessageToDict(response)
result_json = MessageToJson(response)
Run Code Online (Sandbox Code Playgroud)

我收到一条错误消息

>>> result_dict = MessageToDict(response)
Traceback (most recent call last):
  File "/Users/pmehta/Anaconda-3/anaconda3/envs/nlp_36/lib/python3.6/site-packages/proto/message.py", line 555, in __getattr__
    pb_type = self._meta.fields[key].pb_type
KeyError: 'DESCRIPTOR'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/pmehta/Anaconda-3/anaconda3/envs/nlp_36/lib/python3.6/site-packages/google/protobuf/json_format.py", line 175, in MessageToDict
    return printer._MessageToJsonObject(message)
  File "/Users/pmehta/Anaconda-3/anaconda3/envs/nlp_36/lib/python3.6/site-packages/google/protobuf/json_format.py", line 209, in _MessageToJsonObject
    message_descriptor = message.DESCRIPTOR
  File "/Users/pmehta/Anaconda-3/anaconda3/envs/nlp_36/lib/python3.6/site-packages/proto/message.py", line 560, in __getattr__
    raise AttributeError(str(ex))
AttributeError: 'DESCRIPTOR'
Run Code Online (Sandbox Code Playgroud)

如何解析此响应以将其正确转换为 json 或 dict?

raj*_*raj 8

作为google-cloud-language 2.0.0 迁移的一部分,响应消息由proto-plus包装原始 protobuf 消息的 提供。ParseDict并且MessageToDict是由protobuf和提供的方法,因为proto-plus包装了 proto 消息,这些 protobuf 方法不能再直接使用。

代替

from google.protobuf.json_format import MessageToDict, MessageToJson 
result_dict = MessageToDict(response)
result_json = MessageToJson(response)
Run Code Online (Sandbox Code Playgroud)

import json
result_json = response.__class__.to_json(response)
result_dict = json.loads(result_json)
result_dict
Run Code Online (Sandbox Code Playgroud)

  • 这并没有真正起作用并产生了错误,但这对我有用:`response.query_result.__dict__` (2认同)