簡體   English   中英

循環遍歷文本文件中的行並解析匹配信息 Python

[英]Loop through lines in a text file and parse matching information 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

您可以繞過 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')]

暫無
暫無

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

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