Seperate groups in input file python

Viewed 37

I am working on an assignment for python and now I have a .txt file with this data

1a
Veronica Pieters__________1.3 4.5 9.3
Erika Verald________3.3 9.9 2.0
=
2a
Rick de jager____________2.2 3.2 4.2
Hendrik Leward__________6.2 1.3 5.5
Veriela beteewr___________9.4 5.4 1.2
Hendrik Loerpo__________4.0 2.5 3.2

Now my question is how can I print the data separated so data for group 1a and data of group 2a

2 Answers

Are you want next result? I storage result information into dictionary res

import re
with open('1.txt') as f:
    groups_data = f.read().split('\n=\n')

res = {}
for group_data in groups_data:
    group_name, people_data = group_data.split('\n', 1)
    print(group_name)
    res[group_name] = {}
    for people_s in people_data.split('\n'):
        name, vals_s = re.compile('([^_]+)_+([^_]+)').findall(people_s)[0]
        vals = tuple(map(float, vals_s.split()))
        print(name, sum(vals)/len(vals))
        res[group_name][name] = sum(vals)/len(vals)

#print(res)

You could do this to get the data into two separate lists. I assumed that the data is separated by the fourth line containing =:

f = open("1.txt","r+")

lines = f.readlines()
idx = lines.index("=\n")
print(idx)
g1 = []
g2 = []
for i in range(idx):
    g1.append(lines[i].strip("\n"))
for j in range(idx,len(lines)):
    g2.append(lines[i].strip("\n"))
print(g1,g2)
Related