![](/img/trans.png)
[英]Python 3: How to loop through a text file and find matching keywords?
[英]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.