使用python的google-cloud-language库如何获取以下方法返回的JSON。
client.classify_text()
client.analyze_entity_sentiment()
方法response.serializetostring()
似乎以无法在python中解码的方式对结果进行编码。不是UTF-8或Unicode转义。
我想要获取JSON,以便可以将其转储到mongodb中。
谢谢。
答案 0 :(得分: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"
}