从python中的文本文件中获取平均分数?

2024-10-03 15:26:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想让程序读取一个文本文件,例如这样的格式

Kristen
100
Maria
75
Frank
23

python中是否存在跳过行并让它只读取数字、累加数字并求平均值的方法?可以比上面的示例多或少。我被卡住了


Tags: 方法frank程序示例格式数字平均值文本文件
3条回答

使用strip删除换行符,使用isdigit检查数字

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

您可以使用re.findall查找字符串中的所有数字:

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)

这是我将使用的方法:

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

相关问题 更多 >