我正在尝试将上面的输入格式格式化为dicts列表。
基本上我想要的是将文件的内容转换为dicts列表。但是,每次运行代码时,我都会得到相同的输出:[{'类似:similar5,'得分':得分5,'复合':smi}]。这意味着只创建了一个dict,当我的目标是创建5个dicts(每行一个)。 有人可以帮我解决这个问题吗?
dt = [] # Creates a list to store dicts
with open('sample_text.out') as f: # Opens the target text file
for line in f:
if line.startswith('Compound'):
smi = line.split()[1]
dt.append({'Compound' : smi}) # Add smi as a value in a dict inside the list 'dt'
else: # This part will iterate over the next few lines, split them and add them to the growing list of dicts
new_line = line.split()
similar = new_line[0]
score = new_line[1]
print new_line
for dicts in dt:
dicts['Similar'] = similar
dicts['Score'] = score
print dt
答案 0 :(得分:1)
这会尝试修复代码中的一些设计缺陷并输出您想要的内容:
dictionaries = [] # Creates a list to store dicts
with open('sample_text.out') as input_file: # Opens the target text file
compound = None
for line in input_file:
if line.startswith('Compound'):
_, smi = line.split()
compound = smi
else:
similar, score = line.split()
dictionaries.append({'Similar': similar, 'Score': score})
dictionaries[-1]['Compound'] = compound
print(dictionaries)