简体   繁体   中英

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.

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)

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")

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
# 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

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM