Basically, this is my task. Extract numbers from a text file and then calculate the sum of them. I wrote the code successfully and but it doesn't work fine with 2 or more digit numbers and negative numbers. What should i do?
f = open('file6.txt', 'r')
suma = 0
file = f.readlines()
for line in file:
for i in line:
if i.isdigit() == True:
suma = int(i)
print("The sum is ", suma)
file6.txt:
1
10
Output:
The sum is 2
CodePudding user response:
In your case, you are going line by line first through the loop and looking at every digit ( in second loop ) to add.
And /n at the end of elements make the .isDigit() function disabled to find the digits.
So your updated code should be like this :
f = open('file6.txt', 'r')
suma = 0
file = f.readlines()
for line in file:
if line.strip().isdigit():
suma = int(line)
print("The sum is ", suma)
Hope it helps!
CodePudding user response:
Use re.split
to split the input into words on anything that is not part of a number. Try to convert the words into numbers, silently skip if this fails.
import re
sum_nums_in_file = 0
with open('file6.txt') as f:
for line in f:
for word in re.split(r'[^- \dEe.] ', line):
try:
num = float(word)
sum_nums_in_file = num
except:
pass
print(f"The sum is {sum_nums_in_file}")
This works for example on files such as this:
-1 2.0e0
3.0