import re path = 'res/01/input' nums = ['zero','one','two','three','four','five','six','seven','eight','nine'] pattern_str = r'one|two|three|four|five|six|seven|eight|nine' result1 = result2 = 0 with open(path, 'r') as file: for line in file: numbers = [c for c in line if c.isdigit()] result1 += int(numbers[0] + numbers[-1]) first = re.search(r'\d|' + pattern_str, line).group() second = re.search(r'\d|' + pattern_str[::-1], line[::-1]).group()[::-1] num = first + ' ' + second for i,n in enumerate(nums): num = num.replace(n,str(i)) result2 += int(num.replace(" ", ""), 10) print(result1) print(result2)