-1
import re
def ReadText()

    total = 0
    text_file = open('Heliatext.txt', 'r')
    lines = text_file.read()
    numblist = []
    print(lines)
    print(len(lines))
    stuff = re.findall(r'\d+', lines)
    numblist.append(stuff)
    print(numblist)
    for x in numblist:
        total += x
        print (total)

    text_file.close()
ReadText()

Hi all, so i'm trying to scrape a simple text file for integers, put them into a list, and then add them all together. I've been looking throughout stackoverflow for how to do this and as far as i can tell, this way should work but i keep on getting this error

Traceback (most recent call last): File "C:/Users/chris/Desktop/Helia.py", line 32, in ReadText() blah blah, 1 File "C:/Users/chris/Desktop/Helia.py", line 28, in ReadText total += x TypeError: unsupported operand type(s) for +=: 'int' and 'list'

file contents are this:

blah blah, 1 this is in he3lia's file 6

Any help and insight is appreciated. You guys are awesome!

Cflux
  • 1,233
  • 2
  • 14
  • 30

3 Answers3

0

You need to convert the entries of your list to integer. try this instead:

for x in stuff:
    total += int(x)
python novice
  • 274
  • 1
  • 4
  • 17
0

re.findall returns strings, so you'll need to coerce the numeric strings to ints. Python's strong typing won't let you add strings together.

You've got some delightful Python discoveries ahead of you! Your 6 lines of iterative code starting stuff = re.findall(...) and finishing print (total) can be written in two lines in Python:

numblist = [int(num) for num in re.findall(r'\d+', lines)]
print(sum(numblist))

Have a read about comprehensions in Python to find out more.

Nick
  • 1,271
  • 11
  • 25
  • lol. itll be a while before i get there. although one day i hope i do. I just ran it and it works. thanks man! in this you are running a for loop inside of a list? is that correct? – Cflux Jun 08 '16 at 16:19
0

There are two problems here: (1) numblist is a list of lists, rather than a flat list, and (2) the list values are strings rather than integers.

You can fix the first problem by using the extend method rather than the append method. You can also use += to do the same thing.

You can fix the second problem by converting the strings to integers, i.e. use int(x) rather than x.

Here's is an updated version of the posted code that fixes these problems:

import re

def ReadText():
    total = 0
    text_file = open('Heliatext.txt', 'r')
    lines = text_file.read()
    numblist = []
    print(lines)
    print(len(lines))
    stuff = re.findall(r'\d+', lines)
    numblist.extend(stuff)
    print(numblist)
    for x in numblist:
        total += int(x)
        print (total)
    text_file.close()

ReadText()
Tom Karzes
  • 20,042
  • 2
  • 16
  • 36