【问题标题】:Python text processing/finding dataPython 文本处理/查找数据
【发布时间】:2017-06-20 16:08:07
【问题描述】:

我正在尝试使用 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)

【问题讨论】:

  • enumerate 帮助您同时访问线路及其索引

标签: python parsing text


【解决方案1】:
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

【讨论】:

  • 我尝试了这段代码,我得到了这个错误:TypeError: 'builtin_function_or_method' object has no attribute 'getitem' 这将需要运行一个包含多个员工的文本文件
  • 是的,这对我来说确实适用于具有多个员工的文本文件。我根据您在问题中的示例数据创建了一个示例文本文件
  • 谢谢。但是我怎样才能绕过这个错误? " TypeError: 'builtin_function_or_method' 对象没有属性 'getitem' "
  • 我发现了我的错误,纠正了它,然后收到了这个错误:" print line[indx+1].strip() Per End: 12/10/2016 IndexError: string index out of范围”此时代码与您的代码完全相同。不知道如何绕过它。
  • 您的线路列表是什么样的?你能像我在 shell 中那样打印它并把它放在这里吗?
【解决方案2】:

我会这样做。

首先,一些测试数据。

test = """SMITH, John\n
Per End: 12/10/2016\n
File:\n
002013\n
Dept:\n
000400\n
Rate:10384 60\n"""

text = [line for line in test.splitlines(keepends=False) if line != ""]

现在是真正的答案。

count_per, count_num = 0, 0

在可迭代对象上使用 enumerate 会自动为您提供索引。

for idx, line in enumerate(text):

    # Just test whether what you're looking for is in the `str`

    if 'Per End' in line:
        print(text[idx - 1]) # access the full set of lines with idx
        count_per += 1
    if 'File:' in line:
        print(text[idx + 1])
        count_num += 1

print("Per Ends = {}".format(count_per))
print("Files = {}".format(count_num))

我的收益:

SMITH, John
002013
Per Ends = 1
Files = 1

【讨论】:

  • 这很好用,但我需要从包含多个员工的文本文件中提取数据。这是否允许我这样做并在每次找到指定字符串时打印此结果?
  • 当然。只需将enumerate(text) 更改为enumerate(lines),并从文件中读取原始lines。我只是想提供测试数据,以便其他人即使没有您的原始文件也可以跟随 - 我训练有素,无法进行测试:)
猜你喜欢
  • 1970-01-01
  • 2017-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-18
  • 1970-01-01
  • 2018-06-10
  • 1970-01-01
相关资源
最近更新 更多