Shaylee Profio
Shaylee Profio

Reputation: 35

How to process words and numbers in a file in python

def sum_numbers_in_file(filename):
    """reads all the numbers in a file and returns the sum of the numbers"""
    filename = open(filename)
    lines = filename.readlines() 
    result = 0
    for num in lines:
        result = result + int(num)
        num.rstrip()
    filename.close()
    return result

answer = sum_numbers_in_file('sum_nums_test_01.txt')
print(answer)

This is in the file:

1
Pango
2
Whero
3
4
10
Kikorangi
20
40
100
-3
4
5

Upvotes: 1

Views: 135

Answers (4)

Daniel
Daniel

Reputation: 485

You can easily add a try-except statement inside the function to make it work only on numbers:

def sum_numbers_in_file(filename):
    """reads all the numbers in a file and returns the sum of the numbers"""
    filename = open(filename)
    lines = filename.readlines() 
    result = 0
    for num in lines:
        try:
            result = result + int(num)
            num.rstrip()
        except ValueError:
            pass
    filename.close()
    return result

answer = sum_numbers_in_file('sum_nums_test_01.txt')
print(answer)

Or you can use the isalpha method:

def sum_numbers_in_file(filename):
    """reads all the numbers in a file and returns the sum of the numbers"""
    filename = open(filename)
    lines = filename.readlines() 
    result = 0
    for num in lines:
        num = num.rstrip()
        if not num.isalpha():
            result = result + int(num)
    filename.close()
    return result

answer = sum_numbers_in_file('sum_nums_test_01.txt')
print(answer)

The isalpha() returns true only if the string doesn't contain symbols or numbers, so you can use it to check if the string is a number. Also works on decimal numbers.
Note that it also detects symbols as numbers, so if there's a symbol in the line it will count that as a number, potentially generating errors!

Upvotes: 1

sushanth
sushanth

Reputation: 8302

Here are couple of way's you can try using isdigit,

value = 0

with open("sum_nums_test_01.txt") as f:
    for l in f.readlines():
        if l.strip().isdigit():
            value += int(l)

with open("sum_nums_test_01.txt") as f:
    value = sum(int(f) for f in f.readlines() if f.strip().isdigit())

Upvotes: 0

gmdev
gmdev

Reputation: 3155

I would suggest using a try/except block:

with open("words.txt") as f:
    nums = []
    for l in f:
        try:
            nums.append(float(l))
        except ValueError:
            pass

    result = sum(nums)

A simple one-liner that you could implement to get all numerical values if you want an alternative would be:

with open("words.txt") as f:
    nums = [float(l.strip()) for l in f if not l.strip().isalpha()]

    result = sum(nums)

Here, I convert each line into a float and append that value to the nums list. If the line is not a numerical value, it will simply just be passed over, hence pass.

You cannot use .isnumeric() as it will only work for strings that contain only integers. This means no decimals or negative numbers.

Upvotes: 1

user14520680
user14520680

Reputation:

You can use a try-except block, an advanced yet effective way of preventing errors. Add this in your for loop:

try:
    result += int(num)
except: pass

Normally it's a good practice to add something in the except clause but we don't want anything so we just pass. The trymeans we try but if we fail we go to the except part.

Upvotes: 1

Related Questions