我想从PDF中提取某个单词的所有实例,例如“math”。 到目前为止,我使用PyPDF2将PDF转换为文本,然后对其执行regex以找到我想要的内容。这是example PFD
当我运行代码而不是返回正则表达式模式“math”时,它返回整个页面的字符串。请帮忙谢谢
#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)
我收到的不是“math”的所有实例:
^{pr2}$等等
TextVersion
变量保存文本。当您将它用于for
循环时,它将一次为文本提供一个字符,如您所见。findall
函数将返回一个匹配列表,因此,如果您将其用于for
循环,您将得到每个单词(在测试中都是相同的)。在
^{pr2}$findall
返回的结果如下:因此,您的输出将是:
实际上,您正在迭代
TextVersion
变量的值。必须遍历re.findall
返回的列表。在所以你的for循环必须是
相关问题 更多 >
编程相关推荐