I am using python to parse a txt file. My text file looks like this:
Text below here:
Master : 000000 Slave : 000001 000002
Master : 000003 Slave : 000004 000005
Master : 000006 Slave : 000007 000008
Master : 000010 Slave :
Master : 000012 Slave :
Master : 000014 Slave :
Master : 000016 Slave : 000017 000018
Master : 000020 Slave : 000021 000022
Master : 000024 Slave : 000025 000026
Master : 000028 Slave : 000029 000030
Master : 000032 Slave : 000033 000034
Master : 000036 Slave : 000037 000038
I want all these values inside a dictionary with master as keys and slaves as values.
{master1: [slave1, slave2], master2: [slave1, slave2]}
KEYS VALUES
00000 00001 , 00002
00003 00004 , 00005...
I am a python newbie. Please help. Thank you
CodePudding user response:
You can use re
module and regular expressions to find the master and slave values with a pattern, then simply get the groups from the pattern and add them to the dictionary accordingly:
import re
pattern = re.compile(r'Master : (.*) Slave : (.*)')
file_name = 'myfile.txt'
dct = {}
with open(file_name, 'r') as file:
for line in file:
match = pattern.match(line.strip())
if match:
master, slave = match.groups()
dct[master] = slave.split()
print(dct)
Output:
{'000000': ['000001', '000002'],
'000003': ['000004', '000005'],
'000006': ['000007', '000008'],
'000016': ['000017', '000018'],
'000020': ['000021', '000022'],
'000024': ['000025', '000026'],
'000028': ['000029', '000030'],
'000032': ['000033', '000034'],
'000036': ['000037', '000038']}
Useful:
CodePudding user response:
This would be my solution
dictionary = {}
with open('text.txt', 'r') as file:
for line in file:
slaves = line.split('Slave :')[1].strip()
master = line.split('Slave :')[0].split('Master : ')[1].strip()
list_of_slaves = slaves.split()
dictionary[master] = list_of_slaves
It gave this as result
{'000000': ['000001', '000002'],
'000003': ['000004', '000005'],
'000006': ['000007', '000008'],
'000010': [],
'000012': [],
'000014': [],
'000016': ['000017', '000018'],
'000020': ['000021', '000022'],
'000024': ['000025', '000026'],
'000028': ['000029', '000030'],
'000032': ['000033', '000034'],
'000036': ['000037', '000038']}