使用输入fi中的信息根据条件生成列表的优雅方法

2024-10-01 02:21:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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']

在这种情况下,如果有更简单的解决方案,那就太好了


Tags: idfalsehomeiflinefilestripsas
1条回答
网友
1楼 · 发布于 2024-10-01 02:21:55

我将使用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)

相关问题 更多 >