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
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字典完全相同,因此您可以将它们视为这样:
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],
...
}
我希望这个数据结构将帮助您计算均值并将其写回到文件中
这是我的解决方案:
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)}")
我知道这有点复杂,但是我保证它将按您的意愿工作。