python - 使用正则表达式替换页脚页码
问题描述
我使用正则表达式从 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。任何指针?
解决方案
假设页脚文本确实包含与 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))
推荐阅读
- python - 如何从大型数据集中删除 NaN
- string - 使字符串看起来等长
- python - Ajax 调用后返回 python 脚本数据
- javascript - 如何使用 Jest/Enzyme 在反应组件中模拟来自 useContext() 的反应“调度”功能
- c# - 选择并计算行数
- javascript - 创建数组副本的JS问题
- python - 在 Python 中模拟重力的问题
- r - 过滤器不响应我闪亮的应用程序中的应用和清除按钮
- c++ - 投射`dlib::matrix的好方法
`进入`dlib::matrix` ? - java - java -cp 相对路径在 git-bash 上不起作用