简体   繁体   中英

Loop through lines in a text file and parse matching information Python

I have a text file that I need to loop through each line and only extract certain matching information. The text file has many lines as below:

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

I need to combine two lines to have results as below:

['1365', 'Tom']

Below is how I attempted it:

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)

Below is the function:

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

You may bypass the 2 header lines, then read the file 2-lines by 2, this can be done with 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')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM