python - 未从 PyPDF2 上的正则表达式接收 PDF 的正确模式

标签 python regex python-3.x pdf pypdf

我想从 PDF 中提取特定单词的所有实例,例如“数学”。 到目前为止,我正在使用 PyPDF2 将 PDF 转换为文本,然后对其进行正则表达式以找到我想要的内容。这是example PFD

当我运行代码而不是返回“数学”的正则表达式模式时,它返回整个页面的字符串。请帮忙谢谢

#First Change Current Working Directory to desktop

import os
os.chdir('/Users/Hussein/Desktop')         #File is located on Desktop


#Second is the PyPDF2

pdfFileObj=open('TEST1.pdf','rb')          #Opening the File
pdfReader=PyPDF2.PdfFileReader(pdfFileObj)
pageObj=pdfReader.getPage(3)               #For the test I only need page 3
TextVersion=pageObj.extractText()
print(TextVersion)



#Third is the Regular Expression

import re
match=re.findall(r'math',TextVersion)
for match in TextVersion:
      print(match)

我收到的不是仅仅获取“数学”的所有实例:

I
n
t
r
o
d
u
c
t
i
o
n

等等等等

最佳答案

TextVersion 变量保存文本。当您将它用于 for 循环时,它会像您所看到的那样一次为您提供一个字符的文本。 findall 函数将返回一个匹配列表,因此,如果您将其用于 for 循环,您将获得每个单词(在您的测试中它们都是相同的) .

import re

for match in re.findall(r'math',TextVersion):
      print(match)

findall 返回的结果类似于:

["math", "math", "math"]

所以你的输出将是:

math
math
math

关于python - 未从 PyPDF2 上的正则表达式接收 PDF 的正确模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32095476/

相关文章:

python - json 格式转换为 float 列表

python - 如何处理 Jupyter Notebook NBextension 配置错误?

python - 需要匹配 2 个不同 pandas 数据框的 2 列(如果匹配),我们需要附加新数据

python - 我在抓取的 JSON 中遇到 KeyError

python - 如何使用python将放置在多个嵌套文件夹中的文档移动和重命名为一个新的单个文件夹?

python - 使用 python 3 抓取需要登录的网站

python - 如何解析没有分隔符的元组?

c# - 如何用括号替换 C# 中的特定单词?

php - 文本预处理的性能改进

regex - 如何解决关于 'filter'字段必须是BSON类型对象的问题