简体   繁体   English

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

[英]How can I find the average of the numbers in a list contained in a string from a text file?

my.txt:我的.txt:

AAAAA -- [4, 2, 1, 2, 4, 2, 4, 4, 5, 2, 2, 1, 5, 2, 4, 3, 1, 1, 3, 3, 5] 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] 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] K -- [4, 1, 2, 1, 2, 1, 2, 5, 1, 1, 1, 1, 4, 2, 2, 1, 5, 1, 3, 4, 1]

How can I make a code that outputs this: (averages of all numbers in each string)我怎样才能制作一个输出这个的代码:(每个字符串中所有数字的平均值)

AAAAA,2.857142857142857

BBB,2.857142857142857

K,2.142857142857143

Note: the code has to work for any other text files contains different numbers/sizes of lists, so I can't just do something like str = "AAAAA -- [4, 2, 1, 2, 4, 2, 4, 4, 5, 2, 2, 1, 5, 2, 4, 3, 1, 1, 3, 3, 5]" and then find the average of this注意:该代码必须适用于包含不同数量/大小的列表的任何其他文本文件,所以我不能只做类似 str = "AAAAA -- [4, 2, 1, 2, 4, 2, 4, 4, 5, 2, 2, 1, 5, 2, 4, 3, 1, 1, 3, 3, 5]" 然后求平均值

the_file = "1.txt"

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

The entries in the file are formatted exactly as ordinary Python dictionaries, so you could treat them as such:文件中条目的格式与普通 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

Now data will be a dictionary like this:现在data将是这样的字典:

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

I hope this data structure will help you calculate the means and write them back to the file我希望这个数据结构能帮助你计算平均值并将它们写回文件

This is my solution:这是我的解决方案:

import re
from os.path import exists


def calculate(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)}")

I know It's a bit complicated, but I guarantee It Will work as you want.我知道这有点复杂,但我保证它会如您所愿地工作。

Okay so I have a pretty simple solution.好的,所以我有一个非常简单的解决方案。

with open('file.txt','r') as f:

    for line in f.readlines():
        try:
            name, l = tuple(line.split('--'))
        except ValueError:
            continue
        name = str.strip(name)
        l = str.strip(l,' []\n')
        l = list(map(int, l.split(',')))
        print("{},{}".format(name, sum(l)/len(l)))

So allow me to explain this to you.所以请允许我向您解释一下。 All I did is read the file, then split them with -- delimiter, then strip the white space in name and then, striped white space, new line character and third bracket.我所做的就是读取文件,然后用--定界符将它们分开,然后去掉名称中的空格,然后是条纹空格、换行符和第三个括号。 Then I split the list elements by , then mapped them to int using map function.然后我将列表元素拆分为,然后使用map函数将它们映射到int If you are not familiar with map then you can also use list comprehension.如果您不熟悉map ,那么您也可以使用列表理解。 Then, I simply calculated the average and print it.然后,我简单地计算平均值并打印出来。

If you are not familiar with map , just replace the line with l = [int(i) for i in l.split(',')] and it should work just fine.如果您不熟悉map ,只需将这一行替换为l = [int(i) for i in l.split(',')] ,它应该可以正常工作。
Hope it helps you.希望对你有帮助。 Cheers:)干杯:)

暂无
暂无

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

相关问题 如何从文本文件python中的数字列表中找到平均值 - How to find the average from a list of numbers in a text file python 如何从文本文件中的数字列表中找到数字的小数位数 - How can I find the amount of decimal places of a number from a list of numbers in a text file 如何从文本文件中找到拆分浮动列表的平均值? - How to find the average of a split float list from a text file? 如何从文本文件中读取值并计算值重复多少次,然后求平均值? - How can I read in values from a text file and calculate how many times a value repeats and then find the average? 如何在Python 3.5.2中从文本文件创建平均值? - How can I create an average from a text file in Python 3.5.2? 如何在python中读取文本文件的列表中推送数字 - How can I push numbers in a list that read in text file in python 如何删除包含在同一字符串列表中的其他字符串中的字符串? - How can I drop strings contained in other string contained in the same string list? 如何从字符串中找到所有四位数字? - How can I find all four digit numbers from string? Python,如何将包含字符串的文本文件转换为列表,以便随后可以计算这些数字的均值和方差 - Python, How do I convert a text file containing a string into a list, so that I can then calculate the mean and variance of those numbers 从文本文件输入的数字的平均值 - Average of numbers input from a text file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM