使用Python regex捕获具有相似模式的列



我正在使用regex和Python抓取pdf。模式在每一列中重复。我不明白如何分别针对每一列信息。

文本字符串:


2000 2001 2002 2003n
14,756 10,922 9,745 12,861n
9,882 11,568 8,176 10,483n
13,925 10,724 10,032 8,927n

我需要按年返回数据,如:

[('2000', '14,756', '9,882', '13,925'),
('2001', '10,922', '11,568', '10,742'),
('2002', '9,745', '8,176', '10,032'),
('2003', '12,861', '10,483', '8,927')]

一旦我有了正则表达式,我就知道如何从页面中取出它并将其放入df中。我只是不明白如何分别针对这些列。我只是一次捕捉到所有的东西。

恐怕不可能捕获列,但您可以将regex与匹配列的组结合起来,并与zip转置。

(?:^|n)([d,]+)s([d,]+)s([d,]+)s([d,]+)(?:$|n)

查看这个正则表达式是如何工作的

import re
text = """2000 2001 2002 2003
14,756 10,922 9,745 12,861
9,882 11,568 8,176 10,483
13,925 10,724 10,032 8,927"""
pattern = r"(?:^|n)([d,]+)s([d,]+)s([d,]+)s([d,]+)(?:$|n)"
grouped = re.findall(pattern, text, flags=re.M)
columns = list(zip(*grouped))  # the expected result

最新更新