I have a text file that looks like this:
3 & 221/73 \\\
4 & 963/73 \\\
5 & 732/65 \\\
6 & 1106/59 \\\
7 & 647/29 \\\
8 & 1747/49 \\\
9 & 1923/49 \\\
10 & 1601/41 \\\
6 & 512 \\\
I want to load the pairs of numbers into a list or a dictionary.
This is the code I have so far:
L = []
data1 = data.replace (" \\\\", " ")
data2 = data1.replace(" & "," ")
i=0
a=''
b=''
while data2[i] != None:
if(a==''):
while( data2[i] != '' ):
a=a+data2[i]
i = i + 1
while(data2[i] !=''):
b=b+data2[i]
i = i + 1
L.append((int(a),int(b)))
a=''
b=''
i=i+1
But this is the error I get:
"while( data2[i] != '' ): string out of range"
You almost had it, like @Vor mentioned, your conditional statements were the issue. Text files don't end with None
in Python so you can't do data2[i] != ''
and data2[i] != None:
.
with open("data.txt") as f:
L=[]
for line in f:
line=line.replace(" \\\\\\", "").strip() #Replace \\\ and strip newlines
a,b=line.split(' & ') #Split the 2 numbers
L.append((int(a),b)) #Append as a tuple
This approach would output a list of tuples, which you asked for:
>>> L
[(3, '221/73'), (4, '963/73'), (5, '732/65'), (6, '1106/59'), (7, '647/29'), (8, '1747/49'), (9, '1923/49'), (10, '1601/41'), (6, '512')]
Note: In your 3rd last line, when you append to L
, you use int()
on the b
variable. Since the string is in the form of '221/73'
, its not a valid integer. You could split the string and int()
each individual number, but then it would divide the numbers, which is probably not what you want.
Here is a solution that is a bit less C-like and looks more like python. Without being sure what exactly the output is supposed to look like, a first guess lead me to this solution:
result = []
with open("test.txt") as f:
lines = f.readlines()
for l in lines:
l = l.replace('\\', '')
elements = l.split("&")
elements = [x.strip() for x in elements]
result.append((int(elements[0]), elements[1]))
print result
This is the output:
[(3, '221/73'), (4, '963/73'), (5, '732/65'), (6, '1106/59'), (7, '647/29'), (8, '1747/49'), (9, '1923/49'), (10, '1601/41'), (6, '512')]
Note that this is missing error handling, so if the file does not conform to your format, this will probably throw an exception.
I think you want to replace data2[i] != ''
and data2[i] != None:
with something like this i < len(data2)
.
Also your code will fail on that line L.append((int(a),int(b)))
because 221/73
is not a valid literal.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.