Epsilon
Epsilon

Reputation: 3

Python: Extracting numbers from text using simple expressions and appending them to list

I'm trying to extract numbers from a text file (using simple expressions) into a list and then to sum all those numbers (there might be a pair or more of numbers per line).

Code:

import re
file = open('test.txt', 'r')
numlist = list()
hand = file.readlines()

for num in hand:
    x = re.findall('[0-9]+', num)
    if len(x) <1 : continue
    numlist.append(x)

print ('Num List: ', numlist)

Output:

Num List:  
[['3759', '5252', '9461'], ['2795'], ['941'], ['3965', '506'], ['1345'], ['8825'], ['8652'], ['9563', '5021'], ['9716', '9439'], ['5922', '1869', '6659'], ['4931', '8288'], ['1928', '3157', '8418'], ['7019', '3206', '7153'], ['2946', '8190'], ['8822', '1769'], ['2079', '896'], ['5960', '5
        044'], ['8808', '8416'], ['652', '9680', '1624'], ['2202', '9352', '341'], ['1528', '306', '355'], ['3776', '6025'], ['663', '4604', '8259'], ['1447', '3694'], ['2925'], ['9299', '61', '8768'], ['7661', '9442'], ['996', '2011', '5878'], ['3301', '4985', '932'], ['1647'], ['290'], ['9822'], ['5298',
        '324'], ['9334', '3481'], ['5177', '3541'], ['42']]

Expected result: I need all numbers to be on one list and not in several arrays

When I use float() after if and then append() only one value from x (list) is appended into numlist

I'm new to code so I'll appreciate any help, Thank You.

Upvotes: 0

Views: 257

Answers (2)

Epsilon
Epsilon

Reputation: 3

Solution:

import re
file = open('test.txt', 'r')
hand = file.readlines()
numlist = list()

for num in hand:
    x = re.findall('[0-9]+', num)
    if len(x) <1 : continue
    numlist.extend(x)

numlist = [int(i) for i in numlist]
sum = sum(numlist)

print ('Num List:', sum)

@omri_saadon Thanks for your help.

Upvotes: 0

omri_saadon
omri_saadon

Reputation: 10631

Instead of using the append you should use the extend.

append() : It is basically used in python to add, one element.

extend() : Where extend(), is used to merged to lists or insert multiple elements in one list.

The method "append" adds its parameter as a single element to the list, while "extend" gets a list and adds its content

Upvotes: 2

Related Questions