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

How to read Arabic text from PDF using Python script

我有一个用 Python 编写的代码,可以读取 PDF 文件并将其转换为文本文件。

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

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

Traceback (most recent call last): File "C:\Users\test\Downloads\pdf-txt\text maker.py", line 68, in f.write(content) UnicodeEncodeError: 'ascii' codec can't encode character u'\xa9' in position 50: ordinal not in range(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') 什么都不做。 return 值是编码的内容,但你必须将它分配给一个变量。更好的是,打开带有编码的文件,然后将 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)