如何从文本文件中找到包含在字符串中的列表中数字的平均值?

问题描述 投票:1回答:2

my.txt:

AAAAA-[4、2、1、2、4、2、4、4、5、2、2、1、5、2、4、3、1、1、3、3、5]

BBB-[5、2、1、2、4、5、4、1、2、2、2、2、4、4、4、3、1、2、3、3、2]

K-[4,1,2,1,2,1,2,5,1,1,1,1,4,2,2,1,1,5,1,4,4,1]

我如何制作输出以下代码:(每个字符串中所有数字的平均值)

AAAAA,2.857142857142857

BBB,2.857142857142857

K,2.142857142857143

注意:该代码必须适用于包含不同数字/大小的列表的任何其他文本文件,所以我不能只做类似str =“ AAAAA-[4,2,1,2,4,4,2, 4,4,5,2,2,1,5,5,4,4,3,1,1,3,3,5]“,然后找到此值的平均值

the_file = "my.txt"

fileRef = open(the_file,"r")      
localList_ofstrings=[]            
for line in fileRef:
    string = line[0:len(line)-1]
    localList_ofstrings.append(string)
    print(string)
fileRef.close()

mean = 0
for char in line:
    number = float(line)
    mean = mean + number
mean = mean/len(lines)
print(mean)

# Output
AAAAA -- [4, 2, 1, 2, 4, 2, 4, 4, 5, 2, 2, 1, 5, 2, 4, 3, 1, 1, 3, 3, 5]
BBB -- [5, 2, 1, 2, 4, 5, 4, 4, 1, 2, 2, 2, 4, 4, 4, 3, 1, 2, 3, 3, 2]
K -- [4, 1, 2, 1, 2, 1, 2, 5, 1, 1, 1, 1, 4, 2, 2, 1, 5, 1, 3, 4, 1
python
2个回答
2
投票

文件中的条目的格式与普通的Python字典完全相同,因此您可以将它们视为这样:

import ast

data = {}
with open(the_file) as f:
    for line in f:
        key, value = line.split('--')
        data[key.strip()] = ast.literal_eval(value.strip())  # parse data as Python list literal

现在data将是这样的字典:

{
    'AAA': [4, 2, 1, 2, 4, 2, 4, 4, 5, 2, 2, 1, 5, 2, 4, 3, 1, 1, 3, 3, 5],
    ...
}

我希望这个数据结构将帮助您计算均值并将其写回到文件中


1
投票

这是我的解决方案:

import re
from os.path import exists


def cal_sum_in_str(path: str):
    pattern_digit = re.compile(r"\d")
    pattern_alpha = re.compile(r"[A-Za-z]")
    digits = []
    alphas = []
    if exists(path):
     try:
        with open(path) as file:
            string = file.read()
        listed_str = string.splitlines()

        for emp_str in listed_str:
            if emp_str == '':
                listed_str.remove(emp_str)

        for number in range(len(listed_str)):
            digits.append(sum([int(n) for n in pattern_digit.findall(listed_str[number])]))

        for alphabet in range(len(listed_str)):      
          alphas.append(''.join(pattern_alpha.findall(listed_str[alphabet])))
     except FileNotFoundError:
       return "No such file or directory found"


    for p in range(len(alphas)):
        print(f"{alphas[p]}---- {digits[p] / len(digits)}")

我知道这有点复杂,但是我保证它将按您的意愿工作。

© www.soinside.com 2019 - 2024. All rights reserved.