Hi, I need to extract numbers from a text file in python. Convert string into int and then sum them up.?

It has to be done in a regular expression. But in my code, it is not converting all strings to integer What am I missing?

import re

name = input("Enter file:")

handle = open(name)

numbers2 = list()

i=0

valuesum=0

for fh in handle:

    fh= fh.rstrip()

    numbers= re.findall('[0-9]+',fh)

    if len(numbers)!=0:

            numbers2.extend(numbers)

            numbers2[i]= int(numbers2[i])

            valuesum= valuesum+ numbers2[i]

            i=i+1

            continue

print(numbers2)

print(i)

print(valuesum)

3 Answers

Relevance
  • Anonymous
    1 month ago
    Favorite Answer

    import re

    name = input("Enter file:")

    f = open(name, "r")

    count = 0

    sum = 0

    numbers = re.findall('[0-9]+', f.read().rstrip())

    for x in numbers:

        sum += int(x)

        count += 1

    print(numbers)

    print(count)

    print(sum)

    file: data.txt

    one 1

    two 2

    three 3

  • EddieJ
    Lv 7
    1 month ago

    I think you misunderstood the assignment.

    It cannot be done in a regular expression because "it" is undefined.

    Also, we don't have your file.

    if len(numbers)!=0:

    What if it the length is greater than 1?  You don't seem to be handling that. 

    import re

    numbers2 = list ()

    fh = "12 x37z83"

    numbers = re.findall ('[0-9]+', fh)

    print (numbers)

    for x in numbers: numbers2 += [int (x)]

    print (numbers2)

    print (len (numbers2))

    print (sum (numbers2))

  • Damien
    Lv 6
    1 month ago

    lol just use dos for this.

Still have questions? Get your answers by asking now.