首页 > 解决方案 > 遍历文本文件中的行并解析匹配信息 Python

问题描述

我有一个文本文件,我需要遍历每一行并且只提取某些匹配信息。文本文件有很多行,如下所示:

person       loan amount    1 month past due     2 month pass due
-------    ---------------  -----------------   -------------------
Tom          3000              3000                  0.00
1365                           100.00%               0.00%
...
...

我需要合并两行以获得如下结果:

['1365', 'Tom']

以下是我的尝试方式:

with open(filepath) as f:
count=0
for line in f:
    if line.find("----") == -1 and line != '\n' and re.research("person|loan amount|pass due",line) == None:
           l=parse_line(line)
           combine=l
           combine.append(l)

下面是函数:

def parse_line(strIn):
    temp=strIn.rsplit(' ',1)
    out=[]
    out=[temp[0].strip()
return out

标签: pythonregextext

解决方案


您可以绕过 2 个标题行,然后按 2 读取文件 2 行,这可以通过zip

filepath = r"file.txt"
result = []
with open(filepath) as fic:
    lines = fic.readlines()[2:]  # remove header lines
    for name_line, value_line in zip(lines[::2], lines[1::2]):
        name = name_line.split(" ")[0]
        value = value_line.split(" ")[0]
        result.append((value, name))

print(result)  # [('1365', 'Tom'), ('1246', 'Linda')]

推荐阅读