[英]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]
AAAAA,2.857142857142857
BBB,2.857142857142857
K,2.142857142857143
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.