【发布时间】:2023-01-29 22:55:53
【问题描述】:
我在下面使用的代码帮助我比较文件并找到 CSV 文件的差异。
但是我在 CSV 文件中得到的结果是从两个文件中提取的随机行集,或者不是按照文档中的顺序。我怎样才能解决这个问题?有没有更好的方法来比较 PDF?
`from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from io import StringIO
from itertools import chain
import pandas as pd
from time import sleep
from tqdm import tqdm
# List of pdf files to process
pdf_files = ['file1.pdf', 'file2.pdf']
# Create a list to store the text from each PDF
pdf1_text = []
pdf2_text = []
# Iterate through each pdf file
for pdf_file in tqdm(pdf_files):
# Open the pdf file
with open(pdf_file, 'rb') as pdf_now:
# Extract text using pdfminer
rsrcmgr = PDFResourceManager()
sio = StringIO()
codec = 'utf-8'
laparams = LAParams()
device = TextConverter(rsrcmgr, sio, codec=codec, laparams=laparams)
interpreter = PDFPageInterpreter(rsrcmgr, device)
for page in PDFPage.get_pages(pdf_now, set()):
interpreter.process_page(page)
text = sio.getvalue()
text = text.split('\n')
if pdf_file == pdf_files[0]:
pdf1_text.append(text)
else:
pdf2_text.append(text)
device.close()
sio.close()
sleep(20)
pdf1_text = list(chain.from_iterable(pdf1_text))
pdf2_text = list(chain.from_iterable(pdf2_text))
differences = set(pdf1_text).symmetric_difference(pdf2_text)
## Create a new dataframe to hold the differences
differences_df = pd.DataFrame(columns=['pdf1_text', 'pdf2_text'])
# Iterate through the differences and add them to the dataframe
for difference in differences:
# Create a new row in the dataframe with the difference from pdf1 and pdf2
differences_df = differences_df.append({'pdf1_text': difference if difference in pdf1_text else '',
'pdf2_text': difference if difference in pdf2_text else ''}, ignore_index=True)
# Write the dataframe to an excel sheet
differences_df = differences_df.applymap(lambda x: x.encode('unicode_escape').decode('utf-8') if isinstance(x, str) else x)
differences_df.to_excel('differences.xlsx', index=False, engine='openpyxl')`
【问题讨论】:
-
PDF 中的文本不需要按阅读顺序存储——根本不需要按任何特定顺序存储。因此,您将必须提取每一行,然后根据您想要的阅读顺序对每一行进行排序——可能是从左上角到右下角。所有这一切仍然处于假设之下,例如组成单词的字符实际上存储在该序列中 - 两者都不需要这样。虽然这种情况很少见,但确实会发生。使用 PyMuPDF,我将在下面的答案中展示如何快速生成排序的行列表。
标签: python python-3.x pdf pdfminer