[英]Python: Extract values from a text file to create nested dictionary
我有一個文本文件,其中包含多個子索引對象,非常雜亂無章,如下所示:
1:
Name of Object 1
Sub-index 0:
Scale: Q0
Unit: Percent
Description: Object 1 does this
2:
Object 2 yo
Sub-index 0:
Scale: Q0
Unit: Percent
Description: Something important
Sub-index 1:
Scale: 0.125
Unit: Percent
Description: Object 2 does that
我想提取這些對象的名稱、比例和描述,並將它們制成字典。 像這樣的東西:
ObjectDict = {
1: ['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']
}
}
我可以通過這樣做來提取字典鍵:
for line in textfile:
a = line.replace(':', '')
if b.isnumeric():
# this is 1 key
我可以通過執行以下操作“可能”提取 object 的比例和描述值:
if 'Scale' in line: # Store the value
if 'Description' in line: # Store the value
但是,這僅在 object 只有 1 個子索引時才有效。 對於像 Object 2 這樣的多子索引對象,我還不知道該怎么做。 在 Python 3.7 中有一個很好的方法嗎? 謝謝!
編輯:我上面選擇的字典格式只是一個例子。 任何其他格式的字典都可以。 我只是想從一個雜亂無章的文件中提取必要的數據並更正確地存儲它,以便其他文件可以訪問它們。
如果您對 txt 文件中的每個 object 使用字典,您可以遍歷 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)
Output:
{
'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']
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.