Python 仅获取 json 中的特定值

Python only get specific value in json

我在 python 上使用 google 视觉 api 来获取图像上的文字, api returns 这个 json 文本:

text_annotations {
  locale: "en"
  description: "SPEED\n"
  bounding_poly {
    vertices {
      x: 6
      y: 60
    }
    vertices {
      x: 151
      y: 60
    }
    vertices {
      x: 151
      y: 117
    }
    vertices {
      x: 6
      y: 117
    }
  }
}
text_annotations {
  description: "SPEED"
  bounding_poly {
    vertices {
      x: 6
      y: 60
    }
    vertices {
      x: 151
      y: 60
    }
    vertices {
      x: 151
      y: 117
    }
    vertices {
      x: 6
      y: 117
    }
  }
}

如何只获取 description: 值?

我一直在努力:esp = response['description']

但是 returns:

Traceback (most recent call last):
  File "C:\Users\fkahd\PycharmProjects\username\ai2.py", line 27, in <module>
    resp = response['description']
TypeError: 'AnnotateImageResponse' object is not subscriptable

完整代码:

import io
import os
import json

# Imports the Google Cloud client library
from google.cloud import vision

os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r"C:\Users\fkahd\OneDrive\Bureau\zefoy\vision-apixxxxxxxxxxxx.json"

# Instantiates a client
client = vision.ImageAnnotatorClient()

# The name of the image file to annotate
file_name = os.path.abspath(r"C:\Users\fkahd\OneDrive\Bureau\zefoy\captchas\captcha(22).png")

# Loads the image into memory
with io.open(file_name, 'rb') as image_file:
    content = image_file.read()

image = vision.Image(content=content)

# Performs label detection on the image file
response = client.text_detection(image=image)  # returns TextAnnotation
resp = response['description']

JSON filed in python 被类似解释为字典,你可以用类似的方式获取 'description' 的值。这是你必须做的:

var_name = file_name['description']

file_name 应该是打开的 json 文件的名称。

我通过添加获得了想要的文本:

print(response.text_annotations[0].description)

感谢您的“帮助”