为什么我看到“TypeError: string indexes must be integerts”?

我正在学习Python,并试图将GitHub问题转换为可读的形式。使用如何将JSON转换为CSV?< / >上的建议,我得到了这个:

import json
import csv


f = open('issues.json')
data = json.load(f)
f.close()


f = open("issues.csv", "wb+")
csv_file = csv.writer(f)


csv_file.writerow(["gravatar_id", "position", "number", "votes", "created_at", "comments", "body", "title", "updated_at", "html_url", "user", "labels", "state"])


for item in data:
csv_file.writerow([item["gravatar_id"], item["position"], item["number"], item["votes"], item["created_at"], item["comments"], item["body"], item["title"], item["updated_at"], item["html_url"], item["user"], item["labels"], item["state"]])

在“issues.json"是包含我的GitHub问题的JSON文件。当我试着运行它时,我得到

File "foo.py", line 14, in <module>
csv_file.writerow([item["gravatar_id"], item["position"], item["number"], item["votes"], item["created_at"], item["comments"], item["body"], item["title"], item["updated_at"], item["html_url"], item["user"], item["labels"], item["state"]])


TypeError: string indices must be integers

我错过了什么?哪些是“字符串索引”?我敢肯定,一旦我得到这个工作,我将有更多的问题,但现在,我只是喜欢这个工作!

当我将for语句调整为简单的

for item in data:
print item

我得到的是…“issues"——所以我做错了更基本的事情。以下是我的JSON内容:

{"issues": [{"gravatar_id": "44230311a3dcd684b6c5f81bf2ec9f60", "position": 2.0, "number": 263, "votes": 0, "created_at": "2010/09/17 16:06:50 -0700", "comments": 11, "body": "Add missing paging (Older>>) links...

当我打印data时,它看起来非常奇怪地被弄脏了:

{u'issues': [{u'body': u'Add missing paging (Older>>) lin...
1711543 次浏览

item很可能是你代码中的字符串;字符串的下标是方括号中的,例如gravatar_id。所以我首先检查你的data变量,看看你在那里收到了什么;我猜data是一个字符串列表(或者至少是一个包含至少一个字符串的列表),而它应该是一个字典列表。

变量item是一个字符串。索引是这样的:

>>> mystring = 'helloworld'
>>> print mystring[0]
'h'

上面的例子使用字符串的0索引来引用第一个字符。

字符串不能有字符串索引(像字典一样)。所以这行不通:

>>> mystring = 'helloworld'
>>> print mystring['stringindex']
TypeError: string indices must be integers

data是一个dict对象。因此,像这样迭代它:

Python 2

for key, value in data.iteritems():
print key, value

Python 3

for key, value in data.items():
print(key, value)

如果缺少逗号,就会出现这种情况。当我有一个二元组列表时,我遇到了它,每个二元组的第一个位置由一个字符串组成,第二个位置由一个列表组成。在一种情况下,我错误地在元组的第一个组件后省略了逗号,解释器认为我试图索引第一个组件。

切片符号str[a:b]的类型错误


简短的回答

str[a:b]中的两个索引ab之间使用结肠 :而不是逗号 ,:

my_string[0,5]  # wrong ❌
my_string[0:5]  # correct ✅

长回答

当处理字符串片的符号 (a 常用序列操作)时,可能会抛出TypeError,指出索引必须是整数,即使它们显然是整数。

例子

>>> my_string = "Hello, World!"
>>> my_string[0,5]
TypeError: string indices must be integers

显然我们把两个整数作为下标传递给了切片符号,对吧?那么问题是什么呢?

这个错误会让人非常沮丧——尤其是在刚开始学习Python的时候——因为错误信息会有一点误导。

解释

在调用my_string[0,5]时,隐式地将两个整数的tuple传递给切片符号。0,5的值与(0,5)的值相同——即使没有括号。为什么不过?

对于Python解释器来说,后面的逗号,实际上已经足够作为元组来求值了:

>>> my_variable = 0,
>>> type(my_variable)
<class 'tuple'>

所以这次我们明确地做了:

>>> my_string = "Hello, World!"
>>> my_tuple = 0, 5
>>> my_string[my_tuple]
TypeError: string indices must be integers

现在,至少错误消息是有意义的。

解决方案

我们需要将逗号 ,替换为结肠 :来正确地分离这两个整数,而不是将它们解释为tuple:

>>> my_string = "Hello, World!"
>>> my_string[0:5]
'hello'

更清晰、更有帮助的错误消息应该是这样的:

TypeError: string indices must be integers not tuple
^^^^^
(actual type here)

一个好的错误消息应该直接告诉用户他们做错了什么!有了这些信息,找到根本原因并解决问题就容易得多了——你也不必来这里了。

因此,下次当您发现自己有责任编写错误描述消息时,请提醒自己这个示例并将原因(或其他有用的信息)添加到错误消息中!帮助别人(甚至是你未来的自己)理解哪里出了问题。

经验教训

  • 切片表示法使用冒号:分隔其索引(和步长范围,即str[from:to:step])。
  • 元组由逗号,(即t = 1,)定义。
  • 向错误消息中添加一些信息,以便用户了解出错的地方

我有类似的熊猫问题,你需要使用iterrows()函数迭代熊猫数据集用于iterrows的Pandas文档

data = pd.read_csv('foo.csv')
for index,item in data.iterrows():
print('{} {}'.format(item["gravatar_id"], item["position"]))

注意,您需要处理由函数返回的数据集中的索引。

作为经验之谈,当我收到这个错误在Python I 比较函数签名和函数执行情况

例如:

def print_files(file_list, parent_id):
for file in file_list:
print(title: %s, id: %s' % (file['title'], file['id']

因此,如果我用错误的参数顺序调用这个函数,并将列表作为第二个参数,将字符串作为第一个参数:

print_files(parent_id, list_of_files) # <----- Accidentally switching arguments location

该函数将尝试遍历parent_id字符串而不是file_list,它将期望将索引视为指向字符串中特定字符的整数,而不是字符串(titleid)的索引。

这将导致TypeError: string indices must be integers错误。

由于它的动态特性(与Java、c#或Typescript等语言相反),Python不会通知你这个语法错误。

将小写字母转换为大写字母:

str1 = "Hello How are U"


new_str = " "


for i in str1:


if str1[i].islower():


new_str = new_str + str1[i].upper()


print(new_str)

错误:

TypeError:字符串索引必须为整数

解决方案:

for i in range(0, len(str1))
// Use range while iterating the string.
如何读取这个JSON的第一个元素? 当文件像这样出现时

. txt
for i in data[1]:
print("Testing"+i['LocalObservationDateTime'])
这对我没用。 下面是JSON文件

[
{
"LocalObservationDateTime":"2022-09-15T19:05:00+02:00",
"EpochTime":1663261500,
"WeatherText":"Mostly cloudy",
"WeatherIcon":6,
"HasPrecipitation":false,
"PrecipitationType":"None",
"IsDayTime":true,
"Temperature":{
"Metric":{
"Value":11.4,
"Unit":"C",
"UnitType":17
},
"Imperial":{
"Value":52.0,
"Unit":"F",
"UnitType":18
}
},
"RealFeelTemperature":{
"Metric":{
"Value":8.4,
"Unit":"C",
"UnitType":17,
"Phrase":"Chilly"
}
}
},
{
"LocalObservationDateTime":"2022-09-16T19:05:00+02:00",
"EpochTime":1663261500,
"WeatherText":"Mostly cloudy",
"WeatherIcon":6,
"HasPrecipitation":false,
"PrecipitationType":"None",
"IsDayTime":true,
"Temperature":{
"Metric":{
"Value":11.4,
"Unit":"C",
"UnitType":17
},
"Imperial":{
"Value":52.0,
"Unit":"F",
"UnitType":18
}
},
"RealFeelTemperature":{
"Metric":{
"Value":8.4,
"Unit":"C",
"UnitType":17,
"Phrase":"Chilly"
}
}
}
]