python - 我正在尝试通过使用python在pdf文件中搜索一个单词但获取页码来返回完整的句子
问题描述
我正在尝试通过使用python在pdf文件中搜索一个单词但获取页码来返回完整的句子
例如有一句话像
此人进行了洗钱(这句话在第 6 页下方)。我正在尝试获取该句子包含洗钱的特定句子。
代码如下:
import PyPDF2
import re
pattern = "laundering"
fileName = "result.pdf"
object = PyPDF2.PdfFileReader(fileName)
numPages = object.getNumPages()
for i in range(0, numPages):
pageObj = object.getPage(i)
text = pageObj.extractText()
text = text.lower()
for match in re.finditer(pattern, text):
print(f'Page no: {i} | Match: {match}')
输出是:
Page no: 6 | Match: <re.Match object; span=(1688, 1698), match='laundering'>
Page no: 30 | Match: <re.Match object; span=(1452, 1462), match='laundering'>
Page no: 54 | Match: <re.Match object; span=(1690, 1700), match='laundering'>
Page no: 78 | Match: <re.Match object; span=(1652, 1662), match='laundering'>
Page no: 101 | Match: <re.Match object; span=(469, 479), match='laundering'>
Page no: 125 | Match: <re.Match object; span=(1657, 1667), match='laundering'>
我期待像输出:
'Complete sentence', page no 6
'Complete sentence', page no 30
''
''
'Complete sentence', page no 125
解决方案
re.finditer(pattern, text)
正在返回一个iterator of Match object
. 要访问实际匹配的文本,您可以使用match.group(0)
以str
格式返回整个匹配项。
由于您要提取句子而不仅仅是您定义的模式,您需要修改您的正则表达式以捕获它之前和之后的单词。
我会这样做:
tx = '''This is a test1!
this is a test2.
test1.
This is a test3'''
import re
pattern = 'test1'
for m in re.finditer(f"([^!?.]*{pattern}.*[!?.])", tx):
print(m.group(0))
输出:
This is a test1!
test1.
此正则表达式将捕获您的模式之前和之后的所有非标点符号字符。
推荐阅读
- azure-devops - 我可以在 Azure Devops 构建管道中集成 Web 测试(用 Visual Studio 编写)吗
- electron - 设置 BrowserWindow frame: false 禁用点击事件
- prolog - Prolog 程序创建一个包含第一个重复元素的列表
- kubernetes - Is there a way to deploy different sets of pods based on context?
- java - Apache Spark XML 转换为 JavaRDD
- php - Apache mod_rewrite:URL slug 未更新
- opencv - 如何检测自定义复杂对象?
- java - 单击java按钮时如何执行C++代码?
- apache-kafka - 如何避免依赖加载火花流和卡夫卡?
- javascript - 提到的用户的 addRole 不起作用