简体   繁体   English

使用python在文本文件中访问和打印特定标签以及相应的标签元素

[英]Accessing and printing particular label in with the corresponding label elements in a text file using python

I have text file using it i have to access particular labels and elements under it and i have do it for other labels also similarly 我有使用它的文本文件,我必须访问其下的特定标签和元素,并且对其他标签也同样

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

This text file format i have access the particular heading and subheading and also access the elements one by one. 我可以使用这种文本文件格式来访问特定的标题和子标题,也可以一一访问元素。

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]]]

This is one approach. 这是一种方法。

Ex: 例如:

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)

Output: 输出:

[{'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']}}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM