[英]python IndexError: string index out of range
I'm getting the IndexError: string index out of range. 我得到IndexError:字符串索引超出范围。 Each line in the file "document_words" ends with "-99".
文件“ document_words”中的每一行都以“ -99”结尾。 So i think error may be because "-99" is not converted to int.
所以我认为错误可能是因为“ -99”未转换为int。 But i'm not sure.
但是我不确定。 If that is the case how can i convert "-99" to int and break from the loop.
如果是这种情况,我如何将“ -99”转换为int并从循环中中断。
Following is my code: 以下是我的代码:
words=open('words','r')
image=open('document_words','r')
data=open('input','a')
linecount=0
for line in image:
if line.strip():
linecount+=1
image.read()
image.seek(0,0)
while linecount>0:
line1=image.readline().split()
for entry in line1:
num=int(entry)
if (num<0):
print("break from loop")
break
else:
tag=words.readline()[num]
data.write(str(tag)+' ')
data.write('\n')
linecount=linecount-1
data.flush()
data.close()
words.close()
image.close()
You haven't told us which line fails, but this looks like the obvious one 您没有告诉我们哪条线失败,但这看起来很明显
tag = words.readline()[num]
so num
is outside the bounds. 因此
num
超出了范围。 I don't think it is the -99
because it should break in that case. 我不认为它是
-99
因为在这种情况下它应该会损坏。 You can add a try/except to help track it down 您可以添加一个try / except来帮助追踪
try:
tmp = words.readline()
tag = tmp[num]
except IndexError, e:
print tmp, num
EDIT: Looks like you are mixing tabs and spaces for the indenting. 编辑:看起来您正在混合制表符和空格的缩进。 This is a no-no unless you are using 8 character tab-stops
除非您使用8个字符制表位,否则这是一个禁忌
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.