Цель: рассчитать сумму всех чисел в текстовом файле (см. Файл в конце ссылки). Выходная сумма должна быть 313125
Проблема: Вариант 1 возвращает пустой список для re.findall и, таким образом, сумма равна нулю. Я думаю, что проблема, возможно, в том, что переменная 'line' не читается как строка. Вариант 2 работает как положено.
Требуется помощь. Что не так с кодом в Option1?
Option1:
import re
# read the file
fh = open(r"regex_sum_395835.txt", encoding='utf-8')
for lin in fh: # loop to read each line in the file
line = str(lin).strip()
array = re.findall('[0-9]+',line) **# I think this is where the problem exists.**
print("Array is", array) *# test line to print the contents of list. It returns and empty list*
total = 0
for number in array: *# loop through the list to find total of all numbers*
total = total + int(number)
print("Sum is", total) *# print the total of all numbers*
Option 2: эта опция работает, но я хочу понять, почему первая опция не работает
import re
fh = open(r"regex_sum_395835.txt", encoding='utf-8').read()
array = re.findall('[0-9]+',fh)
total = 0
for number in array:
total = total + int(number)
print("Sum is", total)
Ссылка на текстовый файл