I have a text file which includes integers in the text. There are one or more integers in a line or none. I want to find these integers with regular expressions and compute the sum.
I have managed to write the code:
import re
doc = raw_input("File Name:")
text = open(doc)
lst = list()
total = 0
for line in text:
nums = re.findall("[0-9]+", line)
if len(nums) == 0:
continue
for num in nums:
num = int(num)
total += num
print total
But i also want to know the list comprehension version, can someone help?
Since you want to calculate the sum of the numbers after you find them It's better to use a generator expression with re.finditer()
within sum()
. Also if the size of file in not very huge you better to read it at once, rather than one line at a time.
import re
doc = raw_input("File Name:")
with open(doc) as f:
text = f.read()
total = sum(int(g.group(0)) for g in re.finditer(r'\d+', text))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.