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

标签 python pdf utf-8 character-encoding arabic

我有一个用 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') 不执行任何操作。返回值是编码后的内容,但必须将其分配给变量。更好的是,使用编码打开文件,并将 Unicode 字符串写入该文件。 content 似乎是 Unicode 数据。

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

 import io
 f = io.open(name,'w',encoding='utf8')
 f.write(content)
  • 如果没有正确关闭文件,您可能看不到任何内容,因为文件没有刷新到磁盘。您有 f.close 而不是 f.close()。最好使用 with,这样可以确保文件在 block 退出时关闭。
  • 示例:

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

    在Python 3中,您不需要导入和使用io.open,但它仍然可以工作。 open 是等效的。 Python 2 需要 io.open 形式。

    关于python - 如何使用 Python 脚本从 PDF 中读取阿拉伯文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47901824/

    相关文章:

    python - 这个最长公共(public)子序列正确吗?

    android - Mozilla PDF 在三星设备上速度极慢

    php - 在 IE8 中显示 PDF 文件时 header() 的问题

    python - Django 表单字段上传错误文件名错误

    python - 列表分配索引超出范围?

    php - PHP转换为utf8两字节编码数据

    java - 解码 Java 字符/字符串

    python - 如何将编码值存储到数据库中

    python - 如何在Python列表中添加和扩展新行?

    pdf - 使用 github/netlify 上的 hugo 从 markdown 自动构建 PDF