我得到python错误类型错误:字符串索引必须是整数,而不是s

2024-04-20 03:21:22 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我从JSON响应中获得的字典

{u'definitions': [{u'text': u'One venerated for experience, judgment, and wisdom.', u'attribution': u'from The American Heritage\xae Dictionary of the English Language, 4th Edition'}, {u'text': u'Having or exhibiting wisdom and calm judgment.', u'attribution': u'from The American Heritage\xae Dictionary of the English Language, 4th Edition'}, {u'text': u'Proceeding from or marked by wisdom and calm judgment:  sage advice. ', u'attribution': u'from The American Heritage\xae Dictionary of the English Language, 4th Edition'}, {u'text': u'Archaic   Serious; solemn.', u'attribution': u'from The American Heritage\xae Dictionary of the English Language, 4th Edition'}, {u'text': u'Any of various plants of the genus Salvia, especially S. officinalis, having aromatic grayish-green, opposite leaves. Also called ramona.', u'attribution': u'from The American Heritage\xae Dictionary of the English Language, 4th Edition'}, {u'text': u'The leaves of this plant used as a seasoning.', u'attribution': u'from The American Heritage\xae Dictionary of the English Language, 4th Edition'}, {u'text': u'Any of various similar or related plants in the mint family.', u'attribution': u'from The American Heritage\xae Dictionary of the English Language, 4th Edition'}, {u'text': u'Sagebrush.', u'attribution': u'from The American Heritage\xae Dictionary of the English Language, 4th Edition'}]}

我尝试使用以下代码语句访问前两个“文本”:

^{pr2}$

我有我需要的绳子。在

但实际的问题是,当我在我的raspberry pi2上运行相同的代码时,我得到以下错误

TypeError: string indices must be integers, not str

任何帮助都将不胜感激。在


Tags: andofthetextfromdictionaryenglishlanguage
1条回答
网友
1楼 · 发布于 2024-04-20 03:21:22

body["definitions"]正在返回一个字符串,请说“hello”,因此如果您写入:

body["definitions"]["0"]

相当于:

^{pr2}$

从而产生错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers

但如果你写:

"hello"[0]

你会得到:

'h'

相关问题 更多 >