4

私はセンチメント分析でテキストにタグを付けるプロジェクトにGoogle Natural Language APIを使用しています。自分のNL結果をJSONとして保存したい。 Googleに直接HTTPリクエストが行われた場合は、JSON応答が返されます。JSONはGoogleの自然言語APIからオブジェクトをシリアル化できますか? (いいえ__dict__属性)

しかし、提供されているPythonライブラリを使用すると、代わりにオブジェクトが返され、そのオブジェクトは直接JSON直列化できません。今

import os 
import sys 
import oauth2client.client 
from google.cloud.gapic.language.v1beta2 import enums, language_service_client 
from google.cloud.proto.language.v1beta2 import language_service_pb2 

class LanguageReader: 
    # class that parses, stores and reports language data from text 

    def __init__(self, content=None): 

     try: 
      # attempts to autheticate credentials from env variable 
      oauth2client.client.GoogleCredentials.get_application_default() 
     except oauth2client.client.ApplicationDefaultCredentialsError: 
      print("=== ERROR: Google credentials could not be authenticated! ===") 
      print("Current enviroment variable for this process is: {}".format(os.environ['GOOGLE_APPLICATION_CREDENTIALS'])) 
      print("Run:") 
      print(" $ export GOOGLE_APPLICATION_CREDENTIALS=/YOUR_PATH_HERE/YOUR_JSON_KEY_HERE.json") 
      print("to set the authentication credentials manually") 
      sys.exit() 

     self.language_client = language_service_client.LanguageServiceClient() 
     self.document = language_service_pb2.Document() 
     self.document.type = enums.Document.Type.PLAIN_TEXT 
     self.encoding = enums.EncodingType.UTF32 

     self.results = None 

     if content is not None: 
       self.read_content(content) 

    def read_content(self, content): 
     self.document.content = content 
     self.language_client.analyze_sentiment(self.document, self.encoding) 
     self.results = self.language_client.analyze_sentiment(self.document, self.encoding) 

あなたが実行した場合::

sample_text="I love R&B music. Marvin Gaye is the best. 'What's Going On' is one of my favorite songs. It was so sad when Marvin Gaye died." 
resp = LanguageReader(sample_text).results 
print resp 

あなたが得るでしょう:

document_sentiment { 
    magnitude: 2.40000009537 
    score: 0.40000000596 
} 
language: "en" 
sentences { 
    text { 
    content: "I love R&B music." 
    } 
    sentiment { 
    magnitude: 0.800000011921 
    score: 0.800000011921 
    } 
} 
sentences { 
    text { 
    content: "Marvin Gaye is the best." 
    begin_offset: 18 
    } 
    sentiment { 
    magnitude: 0.800000011921 
    score: 0.800000011921 
    } 
} 
sentences { 
    text { 
    content: "\'What\'s Going On\' is one of my favorite songs." 
    begin_offset: 43 
    } 
    sentiment { 
    magnitude: 0.40000000596 
    score: 0.40000000596 
    } 
} 
sentences { 
    text { 
    content: "It was so sad when Marvin Gaye died." 
    begin_offset: 90 
    } 
    sentiment { 
    magnitude: 0.20000000298 
    score: -0.20000000298 
    } 
} 

JSONではありません。ここ

は、私のコードのサンプルです。これはgoogle.cloud.proto.language.v1beta2.language_service_pb2.AnalyzeSentimentResponseオブジェクトのインスタンスです。また、__dict__属性属性がないので、json.dumps()を使用してシリアライズできません。

レスポンスをJSONに指定するか、オブジェクトをJSONにシリアル化する方法を指定できますか?

答えて

2

編集:@Zachは、Googleのprotobufデータ交換フォーマットに注目しました。ドキュメンテーション文字列から

from google.protobuf.json_format import MessageToDict, MessageToJson 

self.dict = MessageToDict(self.results) 
self.json = MessageToJson(self.results) 

:好ましい選択肢は、これらのprotobuf.json_format方法を用いることであろうと思われる

MessageToJson(message, including_default_value_fields=False, preserving_proto_field_name=False) 
    Converts protobuf message to JSON format. 

    Args: 
     message: The protocol buffers message instance to serialize. 
     including_default_value_fields: If True, singular primitive fields, 
      repeated fields, and map fields will always be serialized. If 
      False, only serialize non-empty fields. Singular message fields 
      and oneof fields are not affected by this option. 
     preserving_proto_field_name: If True, use the original proto field 
      names as defined in the .proto file. If False, convert the field 
      names to lowerCamelCase. 

    Returns: 
     A string containing the JSON formatted protocol buffer message. 
+0

は、ご返信いただきありがとうございます。オブジェクトがこのような\ _ \ _ dict__属性を持っていないのはどれくらいの頻度ですか?クラスを自分で定義して初期化する場合、デフォルトではクラスが1つあります。 Googleの自然言語APIが主に別の言語で実装されていた可能性がありますか? –

+1

使い勝手の良さのように見えますが、APIが「ベータ」(?)であればあまり一般的ではありません。問題やPRを提出するといいでしょう。どのパッケージをインストールしていますか? – brennan

+1

私は[これはレポです](https://github.com/GoogleCloudPlatform/google-cloud-python/blob/master/language/google/cloud/proto/language/v1beta2/language_service_pb2.py)、そこからgoogle .cloud.proto.language.v1beta2が実装されています。私はそれが要求を解析してオブジェクトをそこに作っていると思う。私はそのギターに問題を投稿します。 –

関連する問題