首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将google云自然语言实体情感响应转换为Python中的JSON/dict?

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

Stack Overflow用户
提问于 2020-10-21 19:31:26
回答 2查看 1.2K关注 0票数 4

我试图使用google云自然语言API来分析实体情感。

代码语言:javascript
运行
复制
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})

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

代码语言:javascript
运行
复制
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
}

现在,我希望以JSON或字典格式存储整个响应,以便将其存储到数据库中的表中或进行处理。我试着跟踪将实体情感输出转换为JSON属性),但没有成功。

如果我用

代码语言:javascript
运行
复制
from google.protobuf.json_format import MessageToDict, MessageToJson 
result_dict = MessageToDict(response)
result_json = MessageToJson(response)

我说错了

代码语言:javascript
运行
复制
>>> 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'

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-10-22 20:53:24

作为google-cloud-language 2.0.0移徙的一部分,响应消息由包装原始原型消息的proto-plus提供。ParseDictMessageToDictprotobuf提供的方法,由于proto-plus封装了proto消息,所以不能再直接使用这些protobuf方法。

替换

代码语言:javascript
运行
复制
from google.protobuf.json_format import MessageToDict, MessageToJson 
result_dict = MessageToDict(response)
result_json = MessageToJson(response)

使用

代码语言:javascript
运行
复制
import json
result_json = response.__class__.to_json(response)
result_dict = json.loads(result_json)
result_dict
票数 10
EN

Stack Overflow用户

发布于 2020-11-26 00:15:27

tl;博士接受的解决方案不是苹果对苹果的替代。为了恢复原始行为,需要执行以下操作:

代码语言:javascript
运行
复制
from google.protobuf.json_format import MessageToDict
result_dict = MessageToDict(response.__class__.pb(response))

在亲自经历了这些之后,我想指出的是,to_jsonMessageToDict都有很大的变化。参数including_default_value_fieldsuse_integers_for_enums默认为False for MessageToDict,现在它们默认为True for to_json

了解更多信息:https://github.com/googleapis/proto-plus-python/blob/5c14cbaf21e3864a247e0183480903e7640e5460/proto/message.py#L372

以下是to_json正式实现的参考

代码语言:javascript
运行
复制
def to_json(cls, instance, *, use_integers_for_enums=True) -> str:
    """Given a message instance, serialize it to json

    Args:
        instance: An instance of this message type, or something
            compatible (accepted by the type's constructor).
        use_integers_for_enums (Optional(bool)): An option that determines whether enum
            values should be represented by strings (False) or integers (True).
            Default is True.

    Returns:
        str: The json string representation of the protocol buffer.
    """
    return MessageToJson(
        cls.pb(instance),
        use_integers_for_enums=use_integers_for_enums,
        including_default_value_fields=True,
    )
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64470470

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档