2016-09-26 26 views
0

我正在使用Python從JSON響應中提取特定的字符串。錯誤:數組下標不能是字符串

def extract_description(texts): 
"""Returns all the text in text annotations as a single string""" 
document = '' 
for text in texts: 
    try: 
     document += text['description'] 
    except KeyError as e: 
     print('KeyError: %s\n%s' % (e, text)) 
return document 

但我得到的錯誤:Error: array indices cannot be string。我試過使用:

for text in texts: 
    try: 
     if text == 'description': 
      document += text 
    except KeyError as e: 
     print('KeyError: %s\n%s' % (e, text)) 
return document 

但是結果是'',文檔是空的。是否有另一種更好的方法來做到這一點?

文本是:

{u'textAnnotations': [{u'locale': u'eo', u'description': 
    u"...discovered 
    text....", u'boundingPoly': {u'vertices': [{u'y': 32, u'x': 21},  
    {u'y': 32, 
    u'x': 954}, {u'y': 685, u'x': 954}, {u'y': 685, u'x': 
    21}]}}]}]}**strong text** 

此代碼是由谷歌的雲API。 https://github.com/GoogleCloudPlatform/cloud-vision/tree/master/python/text

+1

什麼是'texts'? –

+0

@ScottHunter我編輯了我的問題,看一看 –

+0

您爲'texts'發佈的內容不是有效的Python表達式。但是你的原始Python代碼無效,(縮進很重要)。 –

回答

1

基於什麼texts實際上包含了(什麼被張貼不是一個有效的Python表達式)我最好的猜測,它看起來像你需要的是這樣的:

for text in texts: 
    document += texts[text][0]['description'] 
+0

謝謝,我會嘗試一下,如果它工作不正常upvote :) :) –

+0

它的工作非常感謝:) –