Skip to content

Instantly share code, notes, and snippets.

@MichelleDalalJian
Created October 7, 2017 14:48
Show Gist options
  • Save MichelleDalalJian/4d630b054e647b2d61a5ed9bcc385f10 to your computer and use it in GitHub Desktop.
Save MichelleDalalJian/4d630b054e647b2d61a5ed9bcc385f10 to your computer and use it in GitHub Desktop.
Extracting Data With Regular Expressions Finding Numbers in a Haystack In this assignment you will read through and parse a file with text and numbers. You will extract all the numbers in the file and compute the sum of the numbers. Data Files We provide two files for this assignment. One is a sample file where we give you the sum for your testi…
import re
hand = open("regex_sum_24962.txt")
x=list()
for line in hand:
y = re.findall('[0-9]+',line)
x = x+y
sum=0
for z in x:
sum = sum + int(z)
print(sum)
@Alejandro082005
Copy link

My prompt was
"Actual data: http://py4e-data.dr-chuck.net/regex_sum_2076089.txt (There are 79 values and the sum ends with 942)"

`import re
import urllib.request

url = 'https://py4e-data.dr-chuck.net/regex_sum_2076089.txt'
response = urllib.request.urlopen(url)
data = response.read().decode()
numbers = re.findall('[0-9]+', data)
total_sum = sum(int(num) for num in numbers)

print("Sum:", total_sum)
`
Sum = 391942

This one works

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment