Reputation: 29
I have a program that saves the scores you get in the program in a seperate file, however, the file saves the score as this:
2 4 6 8 9 8
My problem is that I cannot convert these to integers, so that I then can add them all together to a total sum.
This is as far as I have come:
scores = open("scores.txt", "r")
After that everything I have tried just ends up in different errors.
Anyone got any idea of what to do?
Upvotes: 1
Views: 37489
Reputation: 88
There are 2 ways to do this:
The first one is to assume that the other program outputs consistent positive integers with single-space delimiter. You can use this code:
with open('scores.txt', 'r') as f:
lines = f.read();
q = lines.split(' ')
a = sum(map(int, q))
print a
The second solution would be to use regex:
import re
intpattern = '[+-]?\d+'
with open('scores.txt', 'r')as f:
lines = f.read();
m = re.findall(intpattern, lines)
a = sum(map(int, m))
print a
Upvotes: 1
Reputation: 4101
I cannot convert these to integers, so that I then can add them all together to a total sum (which in this case would be 2+4+6+8+9+8 = 37)
You can split a line, cast each string to integer, then sum all the numbers. You might as well store these sums in a list and calculate an average.
Try this:
sums = []
with open("scores.txt", "r") as f:
for line in f:
numbers = line.split() # 2 4 6 8 9 8
s = 0
for number in numbers:
try:
s += int(number)
except:
print 'can not cast to integer'
sums.append(s)
avg = sum(sums) / float(len(sums))
Upvotes: -1
Reputation: 2807
Do it as follows:
with open("scores.txt", "r") as f:
score = f.read() # Read all file in case values are not on a single line
score_ints = [ int(x) for x in score.split() ] # Convert strings to ints
print sum(score_ints) # sum all elements of the list
37
Upvotes: 4
Reputation: 9345
Try:
with open("scores.txt", "r") as f:
for l in f;
print(sum([int(a) for a in l.split()]))
Upvotes: 0
Reputation: 21
This is how far I have come... "scores = open("scores.txt", "r")" After that everything I have tried just ends up in different errors. Anyone got any idea of what to do?
I would recommend splitting the string by delimiter.
You could do that by going line for line through the file.
for line in scores:
splitted_line = line.split(' ')
for values in splitted_line:
value_as_int = int(values)
# ... do something with value now
Another recommendation for scanning and handling large data is numpy in my opinion. There are several functions that will import data for you.
I can recommend for myself the genfromtext function. You can define filling values, delimiter and much more there.
Upvotes: 2
Reputation: 26644
You convert to int by writing int(<variable>)
e.g.
>>> a='3'
>>> type(a)
<type 'str'>
>>> a=int(a)
>>> type(a)
<type 'int'>
Upvotes: 0
Reputation: 1872
You have to convert the scores (which are interpreted as Strings) to Integers.
s = "1"
i = int(s)
Upvotes: 1