ProcessInvalid2020
ProcessInvalid2020

Reputation: 13

Getting average score from a text file in python?

I'm looking to have the program read a text file that is formatted like this for example.

Kristen
100
Maria
75
Frank
23

Is there anyway in python to skip lines and have it read only the numbers, accumulate them, and average them out? Could be more numbers or less numbers than the example above. I'm very much stuck.

Upvotes: 1

Views: 603

Answers (5)

Rishabh
Rishabh

Reputation: 902

you can use re.findall to find all numbers in a string:

import re
if __name__ == "__main__":
    numbers = []
    with open("./file.txt", "r") as f:
        for line in f:
            line = line.strip()
            temp = list(map(lambda x: eval(x), re.findall(r'\d+', line)))
            numbers += temp

    average = sum(numbers) / len(numbers)
    print(average)

Upvotes: 1

Honorable con
Honorable con

Reputation: 333

If the file name 'file.txt'

total = 0
i = 0
with open('file.txt', 'r') as file:
    for line in file:
        try:
            total += int(line)
            i += 1
        except:
            continue

average = total / i

Upvotes: 0

TheLazyScripter
TheLazyScripter

Reputation: 2665

# assuming a score always follows a players name.
with open("path_to_file.ext", "r") as inf:
    print(inf.readlines()[1::2]) # Do something with the result

# only grabbing lines that can be interpreted as numbers
with open("path_to_file.ext", "r") as inf:
    for _ in inf.readlines():
        if _.rstrip().isnumeric():
            print(_.rstrip())  # Do something with the result

Upvotes: 0

Osman Mamun
Osman Mamun

Reputation: 2882

use strip to get rid of newline and isdigit to check for digit

In [8]: with open('a.txt', 'r') as f:
   ...:     s = [int(i.strip()) for i in f if i.strip().isdigit()]
   ...:

In [9]: sum(s)/len(s)
Out[9]: 66.0

Upvotes: 0

dsillman2000
dsillman2000

Reputation: 1026

This is the method I would use:

def get_average(filepath):
    total = 0.0
    with open(filepath, 'r') as f:
        lines = f.readlines()
        numbers = 0
        for line in lines:
            try:
                number = int(line.strip())
                total += number
                numbers += 1
            except:
                continue
    return total / float(numbers)

get_average("path/to/file.txt")

Upvotes: 0

Related Questions