【问题标题】:Python with google cloud language api Problem?Python 与谷歌云语言 api 问题?
【发布时间】:2018-10-30 16:25:56
【问题描述】:

使用 python 的 google-cloud-language 库如何获取从以下方法返回的 JSON。

client.classify_text()
client.analyze_entity_sentiment()

response.serializetostring() 方法似乎以无法在 python 中解码的方式对结果进行编码。不是 UTF-8 或 unicode 转义。 我想获取 JSON,以便将其转储到 mongodb 中。

提前致谢。

【问题讨论】:

    标签: python-3.x google-api google-cloud-platform text-analytics-api


    【解决方案1】:

    您可以使用google.protobuf.json_format.MessageToJson 方法将普通的protobuf 对象序列化为JSON。例如:

    from google.cloud import language
    from google.protobuf.json_format import MessageToJson
    
    client = language.LanguageServiceClient()
    
    document = language.types.Document(
        content='Mona said that jogging is very fun.',
        type='PLAIN_TEXT',
    )
    
    response = client.analyze_entity_sentiment(
        document=document,
        encoding_type='UTF32',
    )
    
    print(MessageToJson(response))
    

    打印:

    {
      "entities": [
        {
          "name": "Mona",
          "type": "PERSON",
          "salience": 0.6080747842788696,
          "mentions": [
            {
              "text": {
                "content": "Mona"
              },
              "type": "PROPER",
              "sentiment": {
                "magnitude": 0.10000000149011612,
                "score": 0.10000000149011612
              }
            }
          ],
          "sentiment": {
            "magnitude": 0.10000000149011612,
            "score": 0.10000000149011612
          }
        },
        {
          "name": "jogging",
          "type": "OTHER",
          "salience": 0.39192524552345276,
          "mentions": [
            {
              "text": {
                "content": "jogging",
                "beginOffset": 15
              },
              "type": "COMMON",
              "sentiment": {
                "magnitude": 0.8999999761581421,
                "score": 0.8999999761581421
              }
            }
          ],
          "sentiment": {
            "magnitude": 0.8999999761581421,
            "score": 0.8999999761581421
          }
        }
      ],
      "language": "en"
    }
    

    【讨论】:

      猜你喜欢
      • 2018-03-06
      • 1970-01-01
      • 1970-01-01
      • 2017-10-25
      • 1970-01-01
      • 2018-11-08
      • 2020-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多