简体   繁体   中英

Avg of values from a text file in python

I have a text file that contains current between multiple ports like:

current from A:
B - 10
C - 6

Current from B:
A - 11
C - 4

Current from C:
A - 5
B - 5

I need to find the avg current between same ports, my output should be like :

current A-B is 10.5
current A-C is 5.5
current B-C is 4.5

I was thinking of using nested key value pair. is there any other way i could solve this in python? The code i was thinking was

import re
pat = re.compile("current from")
current = {}
with open(fileName) as f:
    for line in f:
        if pat.search(line):
            key1 = (line.split()[2])
        elif line != "\n" :
            current[key1][line.split()[0]].append(line.split()[2])
for key1 in current:
  for key2 in current[key1]:
    avg = ((current[key1][key2] + current[key2][key1])/2)  
    print("current " + key1 + "-" + key2 + " is " + str(avg))

how about this

import re, collections

def extraer_data(fname):
    with open(fname) as file:
        for raw in re.split(r'current from', file.read(), flags= re.IGNORECASE ):
            raw = raw.strip()
            if raw:
                key,rest = raw.split(":")
                data = [ (c,int(n)) for c,n in re.findall("(\w+) - (\d+)",rest) ]
                yield (key, data)

def process(fname):
    data = collections.defaultdict(list)
    for p1, ports in extraer_data(fname):
        for p2, val in ports:
            data[frozenset((p1,p2))].append(val)
    for key,val in data.items():
        print( "current {} is {}".format("-".join(sorted(key)), sum(val)/len(val)))

as we are using re, lets try using it to its fullest, or at the very least to the best I can :)

first I take the whole file and divide it at current from which give us this

 A:
B - 10
C - 6

------------------------------------------
 B:
A - 11
C - 4

------------------------------------------
 C:
A - 5
B - 5

from there the extraction is more easy, split at : to get the first letter and finall to get the pairs and process them accordingly

>>> list(extraer_data("test.txt"))
[('A', [('B', 10), ('C', 6)]), ('B', [('A', 11), ('C', 4)]), ('C', [('A', 5), ('B', 5)])]
>>> 

once we get the data from the file in a format as show above, is the turn to group them in pairs, and as the order is irrelevant I pack them in a frozenset so they can be used as an dictionary key, and for said dictionary I use a defaultdict of list and once that everything is tie in a little nice package, the rest is a piece of cake

>>> process("test.txt")
current A-B is 10.5
current B-C is 4.5
current A-C is 5.5
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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