python - 遍历文本文件中的行并解析匹配信息 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')]
推荐阅读
- python - 我如何预填充此更新表单
- sql - 用于查找最近数据并比较行的 SQL 查询
- neo4j - NEO4J - RHEL7 - 无法在空数据库上创建约束
- html - 如何在 HTML 级别集成 PrivateIdentity 身份验证?
- ubuntu-14.04 - 干净地同步到另一个 perforce 标签
- java - 在嵌套数组中使用 Jackson 序列化到一定深度
- excel - 如何让宏在 Excel 表中查找值的所有实例?
- java - Jackson jar与JBoss 7.2模块spring boot war部署冲突
- ios - 模式无法匹配“URLRequest”类型的值
- java - 将 String 值转换为 BigDecimal 并按降序对它们进行排序,然后打印它们