繁体   English   中英

在python中从文本文件的某些行中查找平均值

[英]Finding averages from certain lines of a text file in python

我试图从一个简单的文本文件中收集数字并计算这些数字的平均值。 但是,我需要来自文本文件的两个单独的平均值。 文本文件将采用这种格式。

random string
num 1
num 2
random string
random string
num 1
num 2
random string
random string
num 1 
num 2
random string
random string
num 1
num 2
random string

......等等等等,模式总是这样。

我需要能够分别获得所有 num1 的平均值,然后是所有 num2 的平均值。 数字将是整数。 我可以用什么方法来做到这一点? 也许将它们添加到数组或列表中并以这种方式计算它们? 或者还有其他方法吗?

任何指导或建议将不胜感激。

text = '''random string
1
2
random string
random string
3
4
random string
random string
5
6
random string
random string
7
8
random string'''

您可以使用正则表达式,将成对中的第一个和第二个数字分配到两个不同的列表中,然后执行其余操作:

first=[]
second=[]
for m in re.finditer(r'\n(\d+)\n(\d+)\n', text):
    first.append(int(m.group(1)))
    second.append(int(m.group(2)))

输出:

# The values captured from the text string
>>>first, second
([1, 3, 5, 7], [2, 4, 6, 8])
# Average of first values in the pairs
>>> (sum(first)/len(first))
4.0
# Average of second values in the pairs
>>> (sum(second)/len(second))
5.0

首先打开文件,然后阅读第一行。 然后使用 for 循环并将所有数字添加到总数中,然后除以读取的数字总数。

import os

PATH = os.path.dirname(__file__)

with open(PATH+r"\your_text_file.txt", "r") as file:
    total_first = 0
    total_second = 0
    cardinal = 0   # The cardinal is the number of elements in a set.

    for line in file:   # I know that there is a reccurent pattern in the text file.
        try:
            int(line)
        except ValueError:   # If the line is a string, read the next 2 lines as integers then read a third line and start over.
            cardinal += 1
            total_first += int(file.readline())
            total_second += int(file.readline())
            file.readline()

    average_first = total_first / cardinal
    average_second = total_second / cardinal

您可以使用正则表达式来提取所有数字,然后解决这个问题。

import re

with open('test.txt') as file:
    s = file.read()
    nums = re.findall(r'\d', s)
    nums = [int(num) for num in nums]
    nums.sort()
    print(nums)

这将按升序为您提供文本文件中所有整数的列表。

您可以使用linecache

import linecache
line = linecache.getline(file.txt, line_number) # Note: first line is 1, not 0

一旦您可以访问任何一行,计算平均值就变得微不足道了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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