首页 > 解决方案 > 使用正则表达式替换页脚页码

问题描述

我使用正则表达式从 PDF 中提取了一个页脚。页脚示例如下

footer_text = 'company name. (ABC) Q1 2020 Here is some text 01-Jan-2019   1-888-1234567   www.company.com  2 Copyright 2001-2019 some relevant text here'

我想在我的所有文本中找到这个字符串并用空格替换它,因为在我的文本提取过程中我不需要这个。但是,我在每次更改的文本之间都有页码,因此它不是简单的查找和替换。我可以使用找到页码

result = re.search(r"\s[\d]\s", footer_text)

但我不知道如何在查找和替换过程中用任何数字替换这个 2。任何指针?

标签: pythonregex

解决方案


假设页脚文本确实包含与 r'\s\d+\s` 匹配的内容(我允许页码 >= 10),那么首先您要通过将页码替换为与其匹配的正则表达式来创建正则表达式:

regex = re.sub(r'\\ \d+\\ ', r'\s\d+\s', re.escape(footer_text))

现在,无论页码如何,您都可以匹配任何页脚。那么代码是:

>>> import re
...
... footer_text = 'company name. (ABC) Q1 2020 Here is some text 01-Jan-2019 1-888-1234567 www.company.com 11 Copyright 2001-2019some relevant text h
... ere'
...
... regex = re.sub(r'\\ \d+\\ ', r'\s\d+\s', re.escape(footer_text))
... replacement = ' ' # a single space (should this instead be '' for an empty string?)
...
... some_text = "abc" + footer_text + "def"
... print(regex)
... print(some_text)
... print(re.sub(regex, replacement, some_text))
...
company\ name\.\ \(ABC\)\ Q1\s\d+\sHere\ is\ some\ text\ 01\-Jan\-2019\ 1\-888\-1234567\ www\.company\.com\s\d+\sCopyright\ 2001\-2019some\ relevant\ text\ here
abccompany name. (ABC) Q1 2020 Here is some text 01-Jan-2019 1-888-1234567 www.company.com 11 Copyright 2001-2019some relevant text heredef
abc def

为了更简单的复制:

import re

footer_text = 'company name. (ABC) Q1 2020 Here is some text 01-Jan-2019 1-888-1234567 www.company.com 11 Copyright 2001-2019some relevant text here'

regex = re.sub(r'\\ \d+\\ ', r'\s\d+\s', re.escape(footer_text))
replacement = ' ' # a single space (should this instead be '' for an empty string?)

some_text = "abc" + footer_text + "def"
print(regex)
print(some_text)
print(re.sub(regex, replacement, some_text))

推荐阅读