如何将数据从PDF刮入Excel

2024-06-25 05:57:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从PDF中提取数据并将其保存到excel文件中。这是我需要的pdf:https://www.medicaljournals.se/acta/content_files/files/pdf/98/219/Suppl219.pdf

但是,我需要的不是所有数据,而是以下数据(如下),然后将其保存到不同单元格中的excel中: 从第5页开始,从P001到并包括简介——有一个P编号、标题、人名和简介

目前,我只能将PDF文件转换为文本(下面是我的代码),并将其全部保存在一个单元格中,但我需要将其分离到不同的单元格中

import PyPDF2 as p2

PDFfile = open('Abstract Book from the 5th World Psoriasis and Psoriatic Arthritis 
Conference 2018.pdf', 'rb')
pdfread = p2.PdfFileReader(PDFfile)

pdflist = []

i = 6
while i<pdfread.getNumPages():
  pageinfo = pdfread.getPage(i)
  #print(pageinfo.extractText())
  i = i + 1

  pdflist.append(pageinfo.extractText().replace('\n', ''))

print(pdflist)

Tags: 文件数据httpspdfwwwfilesexcelprint
1条回答
网友
1楼 · 发布于 2024-06-25 05:57:17

您主要需要的是15个大写字母的“header”正则表达式和3位数字的“article”正则表达式字母“p”。 还有一个正则表达式可以帮助您将文本除以任何关键字

article_re = re.compile(r'[P]\d{3}')  #P001: letter 'P' and 3 digits
header_re = re.compile(r'[A-Z\s\-]{15,}|$')  #min 15 UPPERCASE letters, including '\n' '-' and
key_word_delimeters = ['Peoples', 'Introduction','Objectives','Methods','Results','Conclusions','References']

file = open('data.pdf', 'rb')
pdf = pdf.PdfFileReader(file)

text = ''

for i in range(6, 63):
    text += pdf.getPage(i).extractText()  # all text in one variable

articles = []

for article in re.split(article_re, text):
    header = re.match(header_re, article)  # recieving a match
    other_text = re.split(header_re, article)[1]  # recieving other text
    if header:
        header = header.group()            # get text from match
        item = {'header': header}
        first_name_letter = header[-1]     # save the first letter of name to put it in right position. Some kind of HOT BUGFIX
        header = header[:-1]               # cut last character: the first letter of name
        header = header.replace('\n', '')  #delete linebreakers
        header = header.replace('-', '')   #delete line break symbol
        other_text = first_name_letter + other_text
        data_array = re.split(
            'Introduction:|Objectives:|Methods:|Results:|Conclusions:|References:',
            other_text)

        for key, data in zip(key_word_delimeters, data_array):
            item[key] = data.replace('\n', '')
        articles.append(item)

相关问题 更多 >