gpt4 book ai didi

Python白痴时刻: string indices must be integers,不是str

转载 作者:太空宇宙 更新时间:2023-11-03 17:11:12 25 4
gpt4 key购买 nike

我正在尝试将文本文件中的句子列表加载到 Python 中。

input_file = open('goods.txt', 'r')
goods = input_file.readlines()

print('# of goods:', len(goods))
for goodies in goods[:5]:
print(goodies["text"])

我得到的输出是:

TypeError: string indices must be integers, not str

我做错了什么?

最佳答案

goods 是一个列表,而不是一个字典。您不能使用字符串索引列表。

来自Python docs :

file.readlines([sizehint])

Read until EOF using readline() and return a list containing the lines thus read. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read. Objects implementing a file-like interface may choose to ignore sizehint if it cannot be implemented, or cannot be implemented efficiently.

您的代码应如下所示:

file = open('goods.txt', 'r')
goods = file.readlines()

print('# of goods:', len(goods))
for i, goodies in enumerate(goods):
print(goodies) # same as print(goods[i])
# example of string manipulation
goods[i] = goods[i].strip()

goods 中的每一项都是一个字符串,其中包含 goods.txt 中的一行。这将打印该文件中的每一行,一次一行。

for 循环中添加 [:5] 将仅迭代文件的前五行(如果您需要的话)。

关于Python白痴时刻: string indices must be integers,不是str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34071836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com