【发布时间】:2021-01-01 11:43:00
【问题描述】:
在上面的 PDF 文件中,我的代码必须从给定 PDF 的所有页面中提取关键字和表名称,例如 Table 1、Table 2、带有粗体字母的标题,例如 INTRODUCTION、CASE PRESENTATION。
写了一个小程序从PDF文件中提取文本
punctuations = ['(',')',';',':','[',']',',','^','=','-','!','.','{','}','/','#','^','&']
stop_words = stopwords.words('English')
keywords = [word for word in tokens if not word in stop_words and not word in punctuations]
print(keywords)
我得到的输出如下
从上面的输出中,如何提取 INTRODUCTION、CASE PRESENTATION、Table 1 等关键字以及页码并将它们保存在输出文件中。
输出格式
INTRODUCTION in Page 1
CASE PRESENTATION in Page 3
Table 1 (Descriptive Statistics) in Page 5
在获取此格式的输出时需要帮助。
代码
def main():
file_name = open("Test1.pdf","rb")
readpdf = PyPDF2.PdfFileReader(file_name)
#Parse thru each page to extract the texts
pdfPages = readpdf.numPages
count=0
text=""
print()
#The while loop will read each page.
while count < pdfPages:
pageObj = readpdf.getPage(count)
count +=1
text += pageObj.extractText()
#This if statement exists to check if the above library returned words. It's done because PyPDF2 cannot read scanned files.
if text != "":
text = text
#If the above returns as False, we run the OCR library textract to #convert scanned/image based PDF files into text.
else:
text = textract.process(fileurl, method='tesseract', language='eng')
#PRINT THE TEXT EXTRACTED FROM GIVEN PDF
#print(text)
#The function will break text into individual words
tokens = word_tokenize(text)
#print('TOKENS')
#print(tokens)
#Clean the punctuations not required.
punctuations = ['(',')',';',':','[',']',',','^','=','-','!','.','{','}','/','#','^','&']
stop_words = stopwords.words('English')
keywords = [word for word in tokens if not word in stop_words and not word in punctuations]
print(keywords)
【问题讨论】:
-
你能不能给我们一个minimal and reproducible example?如果您不显示创建
tokens的代码,我们将无能为力。 -
@LydiavanDyke,我已经编辑了问题并添加了代码
-
请在您的代码中包含导入以及运行它所需的所有其他内容,因此它是minimal reproducible example
-
如果您想获取有关哪个页面是表格的信息,那么您不应该将所有内容放在一个字符串
text += pageObj.extractText()中,但您应该将其保留为字符串列表text = []text.append(pageObj.extractText())并使用每个页面分开(使用for-loop) - 然后您可以轻松识别出哪些文本来自第 1 页、第 2 页等。
标签: python nlp data-science text-extraction