我有一個帶有多個子索引物件的文本檔案,非常無組織,如下所示:
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
我可以通過執行以下操作“可能”提取物件的比例和描述值:
if 'Scale' in line: # Store the value
if 'Description' in line: # Store the value
但是,這僅在物件只有 1 個子索引時才有效。對于像物件 2 這樣的多子索引物件,我還不知道如何去做。在 Python 3.7 中是否有一種很好的方法可以做到這一點?謝謝!
編輯:我上面選擇的字典格式只是一個例子。任何其他格式的字典都可以。我只想從一個無組織的檔案中提取必要的資料并更正確地存盤它,以便其他檔案可以訪問它們。
uj5u.com熱心網友回復:
如果您為 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']
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/391230.html
