首页 > 解决方案 > 我正在尝试通过使用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

标签: pythonpython-3.xpdfnlppypdf2

解决方案


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.

此正则表达式将捕获您的模式之前和之后的所有非标点符号字符。


推荐阅读