如何从 Python 中的 PDF 文件中提取文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15583535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:28:25 来源:igfitidea点击:
How to extract text from a PDF file in Python?
提问by lost
How can I extract text from a PDF file in Python?
如何从 Python 中的 PDF 文件中提取文本?
I tried the following:
我尝试了以下方法:
import sys
import pyPdf
def convertPdf2String(path):
content = ""
pdf = pyPdf.PdfFileReader(file(path, "rb"))
for i in range(0, pdf.getNumPages()):
content += pdf.getPage(i).extractText() + " \n"
content = " ".join(content.replace(u"\xa0", u" ").strip().split())
return content
f = open('a.txt','w+')
f.write(convertPdf2String(sys.argv[1]).encode("ascii","xmlcharrefreplace"))
f.close()
But the result is as follows, rather than readable text:
但结果如下,而不是可读的文本:
728;ˇˆ˜ ˚ˇˇ!""˘ˇˆ˙ˆ˝˛˛˛˛ˆ˜ˆ ˆ ˆ˘ˆ˛˙ˆ"ˆ˘"ˆˆˆ˜#$˙ˆ˚ˆ %&ˆ ˘˛ˆ˜'˙˙%˝˛ˆˇ˙ ˜ˆˆ˜'ˆ ˇˆ#$%&('%$&))$$+%#,-.+&&˝())˝)˝+,,-./012)(˝)*˝+,-3˙ˆ/0245)6#57+82,55)6#57+,+2,+ /!#!!&˘˘1"%˘20˛˛3ˆ07%4!˘"6 ˛ˆ ˝ˆ ˆ˘&/&4"9ˆ %6ˇ%4%4&5˘2)˘˘˛%:6(
第728章˝˛ˆˇ˙ ˜ˆˆ˜'ˆ ˇˆ#$%&('%$&))$$ +%#,-.+&&˝())˝)˝+,,-./012)(˝)* ˝+,-3˙ˆ/0245)6#57+82,55)6#57+,+2,+ /!#!!&˘˘1"%˘20˛˛3ˆ07%4!˘"6˛ ˆ˝ˆ ˆ˘&/&4"9ˆ %6ˇ%4%4&5˘2)˘˘˛%:6(
采纳答案by Moj
if you are running linux or mac you can use ps2asciicommand in your code:
如果您运行的是 linux 或 mac,则可以在代码中使用ps2ascii命令:
import os
input="someFile.pdf"
output="out.txt"
os.system(("ps2ascii %s %s") %( input , output))

