-2

as part of a homework, i am supposed to open a file located below, and sum up all the integers within the text from start to end. I tried to run various codes on the web, but they didn't work. The directory is: http://py4e-data.dr-chuck.net/regex_sum_1532566.txt

"Homework assignment" Handling The Data The basic outline of this problem is to read the file, look for integers using the re.findall(), looking for a regular expression of '[0-9]+' and then converting the extracted strings to integers and summing up the integers.

Please can you make sure the indentation is correct on your reply.

Import re
zzz = open(r’http://py4e-data.dr-chuck.net/regex_sum_1532566.txt’)
sum = 0
for line in zzz:
    line = line.rstrip()
    y = re.findall(‘[0-9]+’,line)
    for blaba in y:
        x= int(blaba)
        sum = sum +x
print (sum)

code

  • You can't `open` a HTTP url, `open` only works with local files. But more importantly, you should tell us what's wrong with the code. Just saying "it didn't work" is too vague. – Aran-Fey May 15 '22 at 10:54
  • Just as the comment above you need to open the file with `requests`, then access the text with `response.text`, and do the rest. Here's a quick solution: ```import numpy as np import requests r=requests.get('http://py4e-data.dr-chuck.net/regex_sum_1532566.txt') rep=re.findall('[0-9]+',r.text) np.sum([int(x) for x in rep])``` – Working dollar May 15 '22 at 12:21
  • @Workingdollar You'll be thrilled to hear that python has a built-in `sum` function. No need for numpy there. – Aran-Fey May 15 '22 at 13:48

0 Answers0