我想从 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/