1121_wordとpdfを比較
Q.1
wordを変換したpdfファイルと、元のwordファイルの内容がテキストベースで同一かを調べるpythonプログラムを作成して下さい。差異がある場合は、その場所をページ番号/行番号/テキスト内容で一覧出力して下さい。
A.1
以下にPythonプログラムを示します。このプログラムはPythonのライブラリであるpython-docx
とPyPDF2
を使用してWordとPDFファイルのテキストを抽出し、それらを比較します。
import PyPDF2 from docx import Document def extract_text_from_pdf(file_path): pdf_file_obj = open(file_path, 'rb') pdf_reader = PyPDF2.PdfFileReader(pdf_file_obj) text = '' for page_num in range(pdf_reader.numPages): page_obj = pdf_reader.getPage(page_num) text += page_obj.extractText() pdf_file_obj.close() return text def extract_text_from_docx(file_path): doc = Document(file_path) text = '' for para in doc.paragraphs: text += para.text return text def compare_texts(text1, text2): differences = [] lines1 = text1.split('\n') lines2 = text2.split('\n') for i in range(min(len(lines1), len(lines2))): if lines1[i] != lines2[i]: differences.append((i+1, lines1[i], lines2[i])) return differences def main(): docx_file_path = 'path_to_your_docx_file' pdf_file_path = 'path_to_your_pdf_file' docx_text = extract_text_from_docx(docx_file_path) pdf_text = extract_text_from_pdf(pdf_file_path) differences = compare_texts(docx_text, pdf_text) if differences: print('Differences found:') for diff in differences: print(f'Line {diff[0]}: DOCX: "{diff[1]}" PDF: "{diff[2]}"') else: print('No differences found.') if __name__ == '__main__': main()
このプログラムは、WordとPDFファイルのテキストが完全に一致することを前提としています。しかし、PDFへの変換プロセスは完全に一致するテキストを生成しない場合があります(例えば、改行やスペースの扱いなど)。そのため、このプログラムはあくまで参考の一つとしてご利用ください。
また、このプログラムはページ番号を出力しないため、ページ番号を出力するにはPDFとWordのページ区切りを正確に抽出する必要がありますが、これは非常に複雑であり、使用するライブラリやPDFとWordの具体的な内容によります。