我试图使用Python提取包含在这个PDF文件中的文本。
我正在使用PyPDF2包(版本1.27.2),并有以下脚本:
import PyPDF2
with open("sample.pdf", "rb") as pdf_file:
read_pdf = PyPDF2.PdfFileReader(pdf_file)
number_of_pages = read_pdf.getNumPages()
page = read_pdf.pages[0]
page_content = page.extractText()
print(page_content)
当我运行代码时,我得到以下输出,这与PDF文档中包含的输出不同:
! " # $ % # $ % &% $ &' ( ) * % + , - % . / 0 1 ' * 2 3% 4
5
' % 1 $ # 2 6 % 3/ % 7 / ) ) / 8 % &) / 2 6 % 8 # 3" % 3" * % 31 3/ 9 # &)
%
如何提取PDF文档中的文本?
目的:从PDF中提取文本
所需工具:
Poppler for windows: windows中pdftotext文件的包装器
对于anaanaconda: conda install -c conda-forge
pdftotext实用程序转换PDF到文本。
步骤:
安装荡漾。windows操作系统:在env路径下增加“xxx/bin/”
PIP安装pdftotext
import pdftotext
# Load your PDF
with open("Target.pdf", "rb") as f:
pdf = pdftotext.PDF(f)
# Save all text to a txt file.
with open('output.txt', 'w') as f:
f.write("\n\n".join(pdf))
在2020年,上述解决方案并不适用于我正在使用的特定pdf。下面是诀窍。我用的是Windows 10和Python 3.8
测试pdf文件:https://drive.google.com/file/d/1aUfQAlvq5hA9kz2c9CyJADiY3KpY3-Vn/view?usp=sharing
#pip install pdfminer.six
import io
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
def convert_pdf_to_txt(path):
'''Convert pdf content from a file path to text
:path the file path
'''
rsrcmgr = PDFResourceManager()
codec = 'utf-8'
laparams = LAParams()
with io.StringIO() as retstr:
with TextConverter(rsrcmgr, retstr, codec=codec,
laparams=laparams) as device:
with open(path, 'rb') as fp:
interpreter = PDFPageInterpreter(rsrcmgr, device)
password = ""
maxpages = 0
caching = True
pagenos = set()
for page in PDFPage.get_pages(fp,
pagenos,
maxpages=maxpages,
password=password,
caching=caching,
check_extractable=True):
interpreter.process_page(page)
return retstr.getvalue()
if __name__ == "__main__":
print(convert_pdf_to_txt('C:\\Path\\To\\Test_PDF.pdf'))
目的:从PDF中提取文本
所需工具:
Poppler for windows: windows中pdftotext文件的包装器
对于anaanaconda: conda install -c conda-forge
pdftotext实用程序转换PDF到文本。
步骤:
安装荡漾。windows操作系统:在env路径下增加“xxx/bin/”
PIP安装pdftotext
import pdftotext
# Load your PDF
with open("Target.pdf", "rb") as f:
pdf = pdftotext.PDF(f)
# Save all text to a txt file.
with open('output.txt', 'w') as f:
f.write("\n\n".join(pdf))
我尝试过许多Python PDF转换器,我想更新这篇评论。蒂卡是最棒的之一。但是PyMuPDF是@ehsaneha用户的好消息。
我做了一个代码来比较一下:https://github.com/erfelipe/PDFtextExtraction希望对大家有所帮助。
Tika-Python是Apache Tika™REST服务的Python绑定
允许在Python社区中本地调用Tika。
from tika import parser
raw = parser.from_file("///Users/Documents/Textos/Texto1.pdf")
raw = str(raw)
safe_text = raw.encode('utf-8', errors='ignore')
safe_text = str(safe_text).replace("\n", "").replace("\\", "")
print('--- safe text ---' )
print( safe_text )