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

问题描述 投票:1回答:1

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

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

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

回溯(最近一次调用最后一次):文件“C:\ Users \ test \ Downloads \ pdf-txt \ text maker.py”,第68行,在f.write(内容)中UnicodeEncodeError:'ascii'编解码器无法编码字符u'\ xa9'位置50:序数不在范围内(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
python pdf utf-8 character-encoding arabic
1个回答
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表单。

© www.soinside.com 2019 - 2024. All rights reserved.