簡體   English   中英

使用輸入文件中的信息根據條件生成列表的優雅方法

[英]Elegant ways to generate lists based on conditions using information from a input file

我有一個看起來像下面的file

file= '/user/home/file.txt'

file

[SKY]
/user/home/repo/study

[EARTH]
/user/home/learn/objects

[LOCAL]
/user/home/teach/files

[SAMP]
VKP
RNP
SAS

[TYPE]
HGH

[SAMP_ID]
VKP_TP_MA
RNP_TP_NA
SAS_SAS

[ENV]
....

現在,我需要將項目從[SAMP][SAMP_ID]轉移到列表中。 這就是我正在做的,正在滿足我的需求。 但是,任何更好或優雅的解決方案都將是不錯的選擇。

所以我的列表是sampsamp_id ,這是解決方案,我目前正在使用,

samp = []
samp_id = []
sampSection = False
samp_idection  =  False

for line in open(file, 'r'):
    if len(line.strip()) == 0:
        sampSection = False
        continue
    if line.strip() == '[SAMP]':
        sampSection = True
        continue
    elif line.startswith('['):
        sampSection = False
        continue
    if sampSection:
        samp.append(line.strip())
        continue

for line in open(file, 'r'):
    if len(line.strip()) == 0:
        samp_idection = False
        continue
    if line.strip() == '[SAMP_ID]':
        samp_idection = True
        continue
    elif line.startswith('['):
        samp_idection = False
        continue
    if samp_idection:
        samp_id.append(line.strip())
        continue

sampsamp_id如下所示,

samp =['VKP','RNP', 'SAS']
samp_id=['VKP_TP_MA','RNP_TP_NA', 'SAS_SAS']

如果在這種情況下有任何更簡單的解決方案,那就太好了。

我將用dict解析整個文件,而無需兩次打開和迭代該文件:

result    = {}
current   = None
with open("my_file.txt") as fd: #To close the file automatically
    for line in fd:
        line = line.strip()
        if line.startswith('['):
            current = line.strip('[]')
            result[current] = []
            continue
        if current is None: continue
        if line: result[current].append(line)

 #Or just use the dictionary
 samp    = result['SAMP']
 samp_id = result['SAMP_ID']

如果您確實不想保留任何其他標簽:

fields    = set(('SAMP','SAMP_ID'))
result    = {}
current   = None
with open("my_file.txt") as fd:
    for line in fd:
        line = line.strip()
        if line.startswith('['):
            current = line.strip('[]')
            if current not in fields: current = None
            else: result[current] = []
            continue
        if current is None: continue
        if line: result[current].append(line)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM