Read Text File To Store Data In A Nested List
I have the following input file with the format as below. SOME TEXT SOME TEXT SOME TEXT SOME TEXT RETCODE = 0 A = 1 B = 5
Solution 1:
You can do something like this:
import re
BLOCK_END = "--- ENDBLOCK"
LETTER_TO_VALUE_REGEX = re.compile(r"\s+(?P<letter>[A-G]) = (?P<number>\d*)")
LETTERS = ["A", "B", "C", "D", "E", "F", "G"]
SUB_BLOCK_END = "\n\n"
top_list = []
for block in text.split(BLOCK_END):
ifnot block:
continue
sub_list = []
for sub_block in block.split(SUB_BLOCK_END):
ifnot sub_block:
continue
letters_to_numbers_dict = {}
for line in sub_block.split("\n"):
match = LETTER_TO_VALUE_REGEX.match(line)
if match:
letters_to_numbers_dict[match["letter"]] = int(match["number"])
inner_list = []
for letter in LETTERS:
inner_list.append(letters_to_numbers_dict.get(letter, ""))
ifset(inner_list) notin [{""}]:
sub_list.append(inner_list)
top_list.append(sub_list)
and then "top_list" is your desired list
Post a Comment for "Read Text File To Store Data In A Nested List"