如何从Python中提取PDF文件中的文本?
我尝试了以下方法:
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()
Run Code Online (Sandbox Code Playgroud)
但结果如下,而不是可读文本:
728;~˚!""˘˙˝˛˛˛˛〜˘˛˙"˘"〜#$˙˚%&˘˛〜'˙% ˝˛˙~~'#$%&('%$&))$ $ +%#, - .+ &&˝())˝) ˝+ ,, - ./ 012)(˝)*˝+, - 3˙/ 0245)6#57 + 82,55)6#57 +,+ 2,+ /!#!!&˘˘1"%˘20˛˛307%4!˘"6˛ ˝˝&/&4"9%6%4%4&5˘2)˘˘˛%:6(
Moj*_*Moj 22
如果您运行的是linux或mac,则可以在代码中使用ps2ascii命令:
import os
input="someFile.pdf"
output="out.txt"
os.system(("ps2ascii %s %s") %( input , output))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
25817 次 |
最近记录: |