如何使用Python脚本从PDF读取阿拉伯文本



我有一个用python编写的代码,该代码从pdf文件中读取并将其转换为文本文件。

当我尝试从PDF文件读取阿拉伯语文本时,就会发生问题。我知道错误是在编码和编码过程中中的错误,但我不知道如何修复它。

系统将转换阿拉伯PDF文件,但文本文件为空。并显示此错误:

trackback(最近的最新通话):文件 " c: users test downloads pdf-txt text maker.py",第68行,in F.Write(content)UnicodeCodeError:'ascii'编解码器无法编码字符u' xa9'位置50:ordinal不在范围内(128)

代码:

import os
from os import chdir, getcwd, listdir, path
import codecs
import pyPdf
from time import strftime
def check_path(prompt):
    ''' (str) -> str
    Verifies if the provided absolute path does exist.
    '''
    abs_path = raw_input(prompt)
    while path.exists(abs_path) != True:
        print "nThe specified path does not exist.n"
        abs_path = raw_input(prompt)
    return abs_path    
print "n"
folder = check_path("Provide absolute path for the folder: ")
list=[]
directory=folder
for root,dirs,files in os.walk(directory):
    for filename in files:
        if filename.endswith('.pdf'):
            t=os.path.join(directory,filename)
            list.append(t)
m=len(list)
print (m)
i=0
while i<=m-1:
    path=list[i]
    print(path)
    head,tail=os.path.split(path)
    var="\"
    tail=tail.replace(".pdf",".txt")
    name=head+var+tail
    content = ""
    # Load PDF into pyPDF
    pdf = pyPdf.PdfFileReader(file(path, "rb"))
            # Iterate pages
    for j in range(0, pdf.getNumPages()):
        # Extract text from page and add to content
        content += pdf.getPage(j).extractText() + "n"
    print strftime("%H:%M:%S"), " pdf  -> txt "
    f=open(name,'w')
    content.encode('utf-8')
    f.write(content)
    f.close
    i=i+1

您有几个问题:

  1. content.encode('utf-8')无需做任何事情。返回值是编码的内容,但是您必须将其分配给变量。更好的是,用编码打开文件,然后将Unicode字符串写入该文件。content似乎是Unicode数据。

示例(适用于Python 2和3):

 import io
 f = io.open(name,'w',encoding='utf8')
 f.write(content)
  1. 如果您不正确关闭文件,则可能不会看到任何内容,因为该文件未冲洗到磁盘。您的f.close不是f.close()。最好使用with,这可以确保块退出时关闭文件。

示例:

import io
with io.open(name,'w',encoding='utf8') as f:
    f.write(content)

在Python 3中,您无需导入和使用io.open,但仍然有效。open是等效的。Python 2需要io.open表格。

您可以使用称为pdfplumber的anthor库,而不是使用pypdf或pypdf2

import arabic_reshaper
from bidi.algorithm import get_display
with pdfplumber.open(r'example.pdf') as pdf:
    my_page = pdf.pages[10]
    thepages=my_page.extract_text()
    reshaped_text = arabic_reshaper.reshape(thepages)
    bidi_text = get_display(reshaped_text)
    print(bidi_text)

最新更新