Reputation: 51
I have to calculate the sum of any numbers in the file and print the sum.
A number is defined as any string beginning with a digit 0 through 9 followed by any number of digits 0 through 9.
Alphanumeric strings (strings including both numbers and letters) are not to be included in the summation.
This is the content of the file:
a b cddde ff 1
5
hH five lll 0
l 10
99 abcd7
9kk
0
So the answer would be 115 in this case.
Upvotes: 1
Views: 3971
Reputation: 1659
def function():
infile = open("test.txt", 'r')
content = infile.read()
infile.close()
wordList = content.split()
total = 0
for i in wordList:
if i.isnumeric():
total += int(i)
return total
In this solution, I named the file test.txt. The idea is you loop through wordList which is a list containing every item spliced in test.txt (try printing wordList before the loop to see for yourself). We then try to cast each item as a int (this assumes no decimals will be in the file, if so you can include a float cast). We then catch ValueError which gets raised when casting i.e 'a' as an int.
Upvotes: -3
Reputation: 3891
All you need to do is use item.isnumeric()
. If the item made up of only numbers and not letters or other characters it will return true.
So you check the all the items in wordList
and if the item isnumeric()
you add the item to total
.
infile = open(filename.txt, 'r')
content = infile.read()
infile.close()
wordList = content.split()
total = 0
for item in wordList:
if item.isnumeric():
total += int(item)
Upvotes: 2
Reputation: 22282
I'd suggest that use RegEx:
import re
with open('file') as f:
print(sum(int(i) for i in re.findall(r'\b\d+\b', f.read())))
In this case:
\b+
match all the numbers, and \b
checks if there a letter after (or before) the number so we can ignore abcd7
or 9kk
.
re.findall()
try to find all the numbers in the file use the RegEx \b\d+\b
and returns a list.
A list compression, int(i) for i in re.findall(r'\b\d+\b')
, convert all the elements in the list which returned by re.findall()
to int
object.
sum()
built-in function sums the elements of a list, and returns the result.
Upvotes: 3