我正在尝试使用 Python 解析/处理文本文件中的一些信息。该文件包含姓名、员工编号和其他数据。我事先不知道姓名或员工编号。我知道在姓名之后有文字:“Per End”,在员工编号之前有文字:“File:”。我可以使用 .find() 方法找到这些项目。但是,我如何让 Python 查看“Per End”和“File:”之前或之后的信息?在这种特定情况下,输出应该是姓名和员工编号。
文本看起来像这样:
SMITH, John
Per End: 12/10/2016
File:
002013
Dept:
000400
Rate:10384 60
因此我的代码是:
file = open("Register.txt", "rt")
lines = file.readlines()
file.close()
countPer = 0
for line in lines:
line = line.strip()
print (line)
if line.find('Per End') != -1:
countPer += 1
print ("Per End #'s: ", countPer)
请您参考如下方法:
file = open("Register.txt", "rt")
lines = file.readlines()
file.close()
for indx, line in enumerate(lines):
line = line.strip()
print (line)
if line.find('Per End') != -1:
print lines[indx-1].strip()
if line.find('File:') != -1:
print lines[indx+1].strip()
enumerate(lines) 也提供对索引和行的访问,在那里您也可以访问上一行和下一行
这是我直接在 python shell 中运行的标准输出:
>>> file = open("r.txt", "rt")
>>> lines = file.readlines()
>>> file.close()
>>> lines
['SMITH, John\n', 'Per End: 12/10/2016\n', 'File:\n', '002013\n', 'Dept:\n', '000400\n', 'Rate:10384 60\n']
>>> for indx, line in enumerate(lines):
... line = line.strip()
... if line.find('Per End') != -1:
... print lines[indx-1].strip()
... if line.find('File:') != -1:
... print lines[indx+1].strip()
SMITH, John
002013
