Reputation: 367
I get this error on the line: if line[0].startswith(element):
I don't know why I am getting this error. Can anyone help. Thank you.
f = open ('testLC31.txt', 'r')
lineCount = 0
toIgnore = ["AND", "ADD", "LEA", "PUTS", "JSR", "LD", "JSRR" , "NOT", "LDI" ,
"LDR", "ST", "STI", "STR", "BR" , "JMP", "TRAP" , "JMP", "RTI" ,
"BR", "ST", "STI" , "STR" , "BRz", "BRn" , "HALT"]
label = []
instructions = []
i = 0
for line in f:
line = line.split()
for element in toIgnore:
if line[0].startswith(element):
lineCount += 1
else:
label.append(line[0])
instructions.append(line[1])
i += 1
lineCount += 1
SAMPLE FILE:
.ORIG x3000
AND R0, R0, #0
AND R1, R1, #0
AND R2, R2, #0
AND R7, R7, #0
LEA R0, MSG1
PUTS
LEA R1, MEMORYSPACE
JSR STRNG
LD R0, NEWLINE
OUT
ADD R0, R1, #0
LD R2, NEG48
ADD R0, R0, R2
PUTS
HALT
MSG1 .STRINGZ "Input a string (length <= 9): "
MEMORYSPACE .BLKW 9
NEWLINE .FILL #10
NEG48 .FILl #-48
.END
Upvotes: 0
Views: 73
Reputation: 25852
there are a few issues with this, I don't know what your requirement is so this is one approach.. but you are adding the exact same word for every instance that its not in the ignore list so there will be a LOT of duplicates. if you want that removed let me know and I can add that for you
for line in f:
if line.split(): #check to see if it is actually something that can be split
elem = line.split()
if len(elem) > 1: #check to see that its more than one word if its not then you are on one of the ignore words
for element in toIgnore:
if elem[0].startswith(element):
lineCount += 1
else:
label.append(elem[0])
instructions.append(elem[1])
i += 1
lineCount += 1
if you want to have unique instructions in your list then you can just do this
f = open ('testLC31.txt', 'r')
line_count = 0
to_ignore = ["AND", "ADD", "LEA", "PUTS", "JSR", "LD", "JSRR" , "NOT", "LDI" ,
"LDR", "ST", "STI", "STR", "BR" , "JMP", "TRAP" , "JMP", "RTI" ,
"BR", "ST", "STI" , "STR" , "BRz", "BRn" , "HALT"]
label = []
instructions = []
i = 0
for line in f:
elem = line.split() if line.split() else ['']
if len(elem) > 1 and elem[0] not in to_ignore:
label.append(elem[0])
instructions.append(elem[1])
i += 1
line_count += 1
elif elem[0] in to_ignore:
line_count += 1
Upvotes: 1
Reputation: 629
The reason you get an index out of range error is that "".split()
results in an empty list []
. Thus when an empty line is read, it leads to an empty list line
, and list[0]
results in an out of range error.
Upvotes: 1