首页 > 解决方案 > 使用 python 和 TypeError 解析特定值:列表索引必须是整数或切片,而不是 str

问题描述

我被这个任务困住了,我似乎无法破解密码。我的意图是解析文本,包含格式如下的行:

date time number

我想用它做一些简单的统计。

棘手的事情是创建一个系统,该系统将int在任何给定日期创建一个只有最高“数字”的 s 列表。

即给出以下内容:

追随者人数.txt

2018-06-11 12:29 692
2018-06-11 12:55 690
2018-06-11 13:00 690
2018-06-11 14:40 690
2018-06-11 15:01 690 <-- this one
2018-06-12 06:00 687
2018-06-12 09:27 688
2018-06-12 09:30 688
2018-06-12 09:37 688
2018-06-12 09:48 688
2018-06-12 10:08 688 <-- this one
2018-06-13 06:00 699
2018-06-13 08:06 700
2018-06-13 10:34 702
2018-06-13 10:40 702 <-- this one
2018-06-14 06:00 709 <-- this one
2018-06-15 06:57 719 <-- this one
2018-06-16 07:50 721 <-- this one

所以在这种情况下,列表将包含690, 688, 702, 709, 719, 721.

我已经来回考虑了一段时间,现在我只是没有选择。另外,我希望每次代码运行时,它都会使用文件中的当前数据创建新列表,并且我似乎能够为它创建一个循环。

这是我已经走了多远:

#open the file and create a list with the lines:

file = open("followerNum.txt").read().splitlines()

#get the first and last 'words' of the first line

date,b,folnum= file[0].split(" ")

#get the first and last 'words' of the second line

date2,b,folnum2 = file[1].split(" ")
#check if it worked
print(date, date2)

for i in file:

  if date2 == date:   #If both are equal, then replace it 
    folnum= file[i].split(" ",-1)
  else:               if not, append 
    folnum.append(file[i].split(" ",-1))

当我运行它时,我得到:

folnum= file[i].split(" ",-1)
TypeError: list indices must be integers or slices, not str

好吧,我希望你能看到这里的菜鸟失败了,你是怎么做到的?看到我会很酷,因为我是一个自学成才的新手:)

标签: pythontext-parsing

解决方案


改变

for i in file:

for i, line in enumerate(file):

这样,我将是一个整数索引而不是一个字符串。线是字符串。


推荐阅读