[英]IndexError: string index out of range:
I'm trying take a .txt file populated by 88 rows, each of which has two characters separated by a space, copy the first character in each row into a list #1, copy the second character of each list into a list #2 and then populate a dictionary with those two lists. 我正在尝试使用一个由88行填充的.txt文件,每行包含两个以空格分隔的字符,将每行中的第一个字符复制到列表#1中,将每个列表的第二个字符复制到列表#2中然后使用这两个列表填充字典。 Something, however, is going wrong when I try to copy down the data from the file into my lists.
但是,当我尝试将文件中的数据复制到我的列表中时,有些东西出错了。 Could you tell me what I'm not doing correctly?
你能告诉我我做得不对吗?
I keep getting this error: "IndexError: string index out of range" at the line where I have typed "column1[count] = readit[0]" 我一直收到这个错误:“IndexError:string index out of range”在我输入的行“column1 [count] = readit [0]”
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()
When you write 当你写作
for line in modo:
filezise+=1
You have already consumed the file. 您已经使用了该文件。 If you want to consume it again, you need to do
modo.seek(0)
first to rewind the file back. 如果你想再次使用它,你需要先做
modo.seek(0)
退文件。
If you do not rewind the file, the line below will return an empty string, because there is nothing left in the file. 如果您不倒回文件,下面的行将返回一个空字符串,因为文件中没有任何内容。
readit = str(modo.readline())
Of course, there's no real need to go through the file twice. 当然,没有必要经过两次文件。 You can just do it once and append to your lists.
您可以只执行一次并附加到列表中。
column1 = []
column2 = []
for line in modo:
filezise+=1
column1.append(line[0])
column2.append(line[2])
尝试这个
codebook = dict([''.join(line.strip().split(' ')) for line in open('codes.txt').readlines()])
You are getting the error because column1 = []*filezise
doesn't actually make a list of length filezise. 您收到错误,因为
column1 = []*filezise
实际上不会生成长度filezise的列表。 (If you look at the result, you will see that column1
is just an empty list.) When you try to access column1[count]
when count > 0
, you will get that error because there is nothing in column1
with an index greater than 0. (如果查看结果,您将看到
column1
只是一个空列表。)当您尝试在count > 0
时访问column1[count]
时,您将收到该错误,因为column1
没有任何索引大于0。
You shouldn't be trying to initialize the list. 您不应该尝试初始化列表。 Instead, iterate over the lines in the file and append the appropriate characters:
相反,迭代文件中的行并附加适当的字符:
column1=[]
column2=[]
for line in file('codes.txt'):
column1.append(line[0])
column2.append(line[2])
There's a much simpler way to get a dictionary from your file, by using the csv
module and the dict()
built-in function: 通过使用
csv
模块和dict()
内置函数,可以更简单地从文件中获取字典:
import csv
with open('codes.txt', 'rb') as csvfile:
codebook = dict(csv.reader(csvfile, delimiter=' '))
So long as the intermediate lists aren't being used, you could also use a dictionary comprehension to do everything in one go. 只要不使用中间列表,您也可以使用字典理解来一次完成所有操作。
with open('codes.txt', 'r') as f:
codebook = {line[0]: line[-1] for line in f.read().splitlines()}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.