I have a .txt file that says “NAMES,” “POINTS” and “SUMMARY” in capital letters, each followed by lines containing data. Each of these three groups is separated by an empty line:
JavaScript
x
15
15
1
NAMES
2
John Cena
3
Sam Smith
4
Selena Gomez
5
6
POINTS
7
sixteen
8
forty
9
thirty
10
11
SUMMARY
12
eighth place
13
sixth place
14
first place
15
My goal is to create three separate sets of names, points and summary.
I already created a set of names using the following code (which outputs a set of all names as intended):
JavaScript
1
11
11
1
names = set()
2
3
for line in open('handout_example.txt'):
4
line = line.strip()
5
if not line:
6
break
7
names.add(line)
8
9
names.remove('NAMES')
10
print(names) #this outputs a set of all names
11
However, I am unsure on how to create a set of points and a set of summary given they’re after an empty line and not at the start of the code unlike names. Any help would be greatly appreciated!! Thank you in advance <3
Advertisement
Answer
here is my solution:
JavaScript
1
24
24
1
names = set()
2
points = set()
3
summary = set()
4
5
next = 0
6
7
for line in open('handout_example.txt'):
8
line = line.strip()
9
if not line:
10
next += 1
11
continue
12
if next == 0:
13
names.add(line)
14
elif next == 1:
15
points.add(line)
16
elif next == 2:
17
summary.add(line)
18
19
names.remove('NAMES')
20
points.remove('POINTS')
21
summary.remove('SUMMARY')
22
23
print(f'{names}t{points}t{summary}')
24
It simple and could be done better but this will work for you I guess.
EDIT: more “pretty” vesrion:
JavaScript
1
14
14
1
nps = dict({'names': set(), 'points': set(), 'summary': set()})
2
nps_n = ['names', 'points', 'summary']
3
4
next = 0
5
6
for line in open('handout_example.txt'):
7
line = line.strip()
8
9
if not line:
10
next += 1
11
continue
12
13
nps[nps[next]].append(line)
14