Извлечение чисел из текстового файла с помощью регулярных выражений. Почему вариант 1 не работает? - PullRequest
0 голосов
/ 29 марта 2020

Цель: рассчитать сумму всех чисел в текстовом файле (см. Файл в конце ссылки). Выходная сумма должна быть 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)

Ссылка на текстовый файл

1 Ответ

3 голосов
/ 29 марта 2020

Код переназначается array для каждой строки. В последней строке файла нет чисел, поэтому конечное значение - пустой список.

Переставьте так, чтобы получить ответ:

import re

# read the file
with open(r"regex_sum_395835.txt", encoding='utf-8') as fh:
    total = 0
    for line in fh: # loop to read each line in the file
        array = re.findall('[0-9]+',line) # I think this is where the problem exists.**
        for number in array: # loop through the list to find total of all numbers*
            total += int(number)

print("Sum is", total) # print the total of all numbers*
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...