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]
列表。这就是我正在做的事情,即给予我需要的东西。但是任何更好或优雅的解决方案都会很棒。
所以我的列表是samp
and samp_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
并且看起来如下samp
,samp_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)
推荐阅读
- python - 使用 Locust 负载测试进行 OAuth 登录
- java - 想要从另一个列表中存在的列表中删除一些元素
- java - 如何获得两个excel列的平均值
- javascript - 如何将时间戳转换为日期格式 yyyy-MM-dd'T'HH:mm:ssXXX?
- python - 在 plotly express 中隐藏图例(不是 Plotly)
- node.js - 当 lambda 中的事件失败时,kinesis 如何保持偏移量并再次推送记录
- jquery - 如何使用 Jquery 检查示例 ajax 函数中是否已存在 3 位代码
- sql - 我如何在日期和时间(小时和分钟)方面加入两行
- excel - 如何从excel文件中删除单元格值匹配条件的行
- node.js - 如何在 express 中为 json2csv 指定配置