简体   繁体   English

使用 Python 正则表达式捕获具有相似模式的列

[英]Capturing columns with similar patterns with Python regex

I'm scraping a pdf using regex and Python. The patterns repeat through each column.我正在使用正则表达式和 Python 抓取 pdf。模式在每一列中重复。 I don't understand how to target each column of information separately.我不明白如何分别定位每一列信息。

Text string:文本字符串:


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

I need to return the data by year like:我需要按年返回数据,例如:

[('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')]

once I have the regex, I understand how to pull it from the page and put it into a df.一旦我有了正则表达式,我就明白了如何将它从页面中拉出来并将其放入 df 中。 I'm just not understanding how to target the columns separately.我只是不明白如何分别定位列。 I just capture everything all at once.我只是一次捕获所有内容。

I am afraid it is impossible to capture columns, but you can combine regex with matching the groups of the columns and transpose with zip .恐怕无法捕获列,但您可以将正则表达式与匹配的列组结合起来,并使用zip进行转置。

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

See how this regex works.看看这个正则表达式是如何工作的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM