【问题标题】:IndexError: string index out of range:IndexError:字符串索引超出范围:
【发布时间】:2014-04-16 03:05:41
【问题描述】:

我正在尝试获取一个由 88 行填充的 .txt 文件,每行有两个由空格分隔的字符,将每行中的第一个字符复制到列表 #1,将每个列表的第二个字符复制到list #2 然后用这两个列表填充字典。但是,当我尝试将文件中的数据复制到我的列表中时,出现了问题。你能告诉我我做错了什么吗?

在我输入“column1[count] = readit[0]”的那一行,我不断收到这个错误:“IndexError: string index out of range”

def main():

    modo = open('codes.txt', 'r')       #opening file
    filezise = 0                        #init'ing counter
    for line in modo:
        filezise+=1                     #counting lines in the file
    column1 = []*filezise
    column2 = []*filezise               #making the lists as large as the file
    count = 0                           #init'ing next counter
    while count < filezise+1:
        readit = str(modo.readline())
        column1[count] = readit[0]      ##looping through the file and
        column2[count] = readit[2]      ##populating the first list with the
        count+=1                        #first character and the second list       
    print(column1, column2)             #with the second character     
    index = 0                               
    n = 0
    codebook = {}                       #init'ing dictionary
    for index, n in enumerate(column1): #looping through to bind the key
        codebook[n] = column2[index]    #to its concordant value
    print(codebook)
main()

【问题讨论】:

  • readit 是一个字符串,而不是一个列表。
  • @Marichyasana,我想他知道这一点,但他仍然可以索引它。

标签: python list dictionary range


【解决方案1】:

当你写作时

 for line in modo:
        filezise+=1  

您已经使用了该文件。 如果你想再次消费,你需要先做modo.seek(0)将文件倒回。

如果不回退文件,下面的行将返回一个空字符串,因为文件中没有任何内容。

readit = str(modo.readline())

当然,没有必要对文件进行两次检查。您只需执行一次并附加到您的列表中。

column1 = []
column2 = []
for line in modo:
   filezise+=1
   column1.append(line[0])
   column2.append(line[2])

【讨论】:

    【解决方案2】:

    试试这个

    codebook =  dict([''.join(line.strip().split(' ')) for line in open('codes.txt').readlines()])
    

    【讨论】:

      【解决方案3】:

      您收到错误是因为column1 = []*filezise 实际上并没有列出长度文件。 (如果您查看结果,您将看到column1 只是一个空列表。)当您尝试访问column1[count] 而count &gt; 0 时,您将收到该错误,因为column1 中没有任何内容索引大于 0。

      您不应该尝试初始化列表。相反,遍历文件中的行并附加适当的字符:

      column1=[]
      column2=[]
      for line in file('codes.txt'):
          column1.append(line[0])
          column2.append(line[2])
      

      【讨论】:

        【解决方案4】:

        使用csv module 和dict() 内置函数可以更简单地从文件中获取字典:

        import csv
        
        with open('codes.txt', 'rb') as csvfile:
            codebook = dict(csv.reader(csvfile, delimiter=' '))
        

        【讨论】:

          【解决方案5】:

          只要不使用中间列表,您还可以使用字典推导式一次性完成所有操作。

          with open('codes.txt', 'r') as f:
              codebook = {line[0]: line[-1] for line in f.read().splitlines()}
          

          【讨论】:

            猜你喜欢
            • 2021-01-30
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-03-26
            • 2012-02-01
            相关资源
            最近更新 更多