如果对txt文件中的每个对象使用字典,则可以循环使用txt文件的行,并使用一些python内置函数,如
readlines()
和
startswith()
做你想做的事。
f = open('sample.txt')
lines = f.readlines()
d = {}
for i,line in enumerate(lines):
if line[:-2].isnumeric():
ind = line[:-2]
name = lines[i+1].replace('\n', '')
if not ind in d:
d[ind] = {}
if line.startswith('Sub-index'):
sub_ind = line.split()[-1].split(':')[0]
if not sub_ind in d[ind]:
d[ind][sub_ind] = []
d[ind][sub_ind].append(name)
if line.startswith('Scale'):
scale = line.split()[-1]
d[ind][sub_ind].append(scale)
if line.startswith('Description'):
desc = line.split(': ')[-1].replace('\n', '')
d[ind][sub_ind].append(desc)
输出:
{
'1': {
'0': ['Name of Object 1', 'Q0', 'Object 1 does this']
},
'2': {
'0': ['Object 2 yo', 'Q0', 'Something important'],
'1': ['Object 2 yo', '0.125', 'Object 2 does that']
}
}