I'm writing a program which reads a big .txt file with lotto numbers. This means that there are always 7 int in one array. (6 from 49 and last one is supernumber).
For example: [[1, 11, 25, 37, 39, 47, 0],[3, 13, 15, 18, 37, 46, 0], ...]
I've got every Month in this .txt which means that it is like
January:
[1, 11, 25, 37, 39, 47, 0]
[3, 13, 15, 18, 37, 46, 2]
[3, 6, 9, 12, 37, 46, 6]
February:
[3, 13, 15, 18, 37, 46, 0]
[1, 23, 17, 18, 37, 46, 8]
...
and so on
How can I generate an array which just reads the numbers of month?
I have a solution but it is very bad coding style:
jan_tipps = []
feb_tipps = []
mar_tipps = []
#variable which month has to be checked
jan = False
feb = False
mar = False
for line in wholefile:
if line == '\n':
pass
elif line == 'January:\n':
jan = True
elif line == 'February:\n':
jan = False
feb = True
elif line == 'March:\n':
feb = False
mar = True
elif jan == True:
jan_tipps.append(line.split())
elif feb == True:
feb_tipps.append(line.split())
elif mar == True:
mar_tipps.append(line.split())
I guess I need something like generics or self generating variables. I don't know what I have to search for in the internet.
As Klaus D. comments, you need a dictionary. But I suspect that is not enough of a hint. Here is a more extended answer.
One issue: Your code doesn't agree with the input data you present. Your code splits the numbers on spaces, but the input data has square brackets and commas instead. This code works with the input you present.
# Parser states:
# 0: waiting for a month name
# 1: expecting numbers in the format [1, 11, 25, 37, 39, 47, 0]
from collections import defaultdict
state = 0
tipps = defaultdict(list)
monthname = None
with open("numbers.txt","r") as f:
for line in f:
if state == 0:
if line.strip().endswith(":"):
monthname = line.split(":")[0]
state = 1
continue
if state == 1:
if line.startswith("["):
line = line.strip().strip("[]")
numbers = line.split(",")
tipps[monthname].append([int(n) for n in numbers])
elif not line.strip():
state = 0
else:
print (f"Unexpected data, parser stuck: {line}")
break
for k,v in tipps.items():
print (f"{k}: {v}")
Output is:
January: [[1, 11, 25, 37, 39, 47, 0], [3, 13, 15, 18, 37, 46, 2], [3, 6, 9, 12, 37, 46, 6]]
February: [[3, 13, 15, 18, 37, 46, 0], [1, 23, 17, 18, 37, 46, 8]]