Saya memiliki file teks yang menggunakannya, saya harus mengakses label dan elemen tertentu di bawahnya dan saya telah melakukannya untuk label lain juga dengan cara yang sama

time[v]
A:
work:35,40
test:89,87

B:
test:89,20

c:
work:56,98

desk[k]:
H:
test:32,34
work:43,46

J:
test:65,98
work:56,90


waat[o]:
M:
test:12,14
work:13,18

q:
test:1,24
work:10,68

Format file teks ini saya memiliki akses ke heading dan subheading tertentu dan juga mengakses elemen satu per satu.

list = ['time[v]:','desk[k]:','waat[o]:']

result=[]
file_open = open(file, 'r')
        lines = [l for l in file_open.read().splitlines()]

        for i in range(len(lines)):
            if lines[i] in list:
                result.append(' '.join(lines).split())
[time[v]::[A:[3540,8987],B:[8920],c:[5698]],
 [desk[k]::[H:[3234,4346],J:[6598,5690]],
 [waat[o]::[M:[1214,1318],q:[124,1068]]]

0
user27895 5 Agustus 2019, 21:34

1 menjawab

Jawaban Terbaik

Ini adalah salah satu pendekatan.

Misalnya:

import re

lst = ['time[v]','desk[k]','waat[o]']
cpy = False
result_temp = []
with open(filename) as infile:
    for line in infile:
        line = line.strip()
        if line:
            if line.startswith(tuple(lst)):   #check for lst 
                result_temp.append([line])
                cpy = True
                continue
            elif re.match(r"[a-z]+\[[a-z]+\]", line):   #check for next key
                cpy = False
            if cpy:
                result_temp[-1].append(line)
result = []
for i in result_temp:
    temp = {}
    for j in i[1:]:
        if re.match(r"[A-za-z]{1}:", j):    #Check for "A:", "B:".....
            key = j
        else:
            temp.setdefault(key, []).append(j.split(":")[1].replace(",", ""))
    result.append({i[0]: temp})  #form output

print(result)

Keluaran:

[{'time[v]': {'A:': ['3540', '8987'], 'B:': ['8920'], 'c:': ['5698']}},
 {'desk[k]:': {'H:': ['3234', '4346'], 'J:': ['6598', '5690']}},
 {'waat[o]:': {'M:': ['1214', '1318'], 'q:': ['124', '1068']}}]
1
Rakesh 29 Agustus 2019, 10:24