You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python解决PDF阿拉伯语文本提取的RTL格式错误问题

解决阿拉伯语PDF文本提取的RTL排版错误问题

PyPDF2对阿拉伯语这类RTL(从右到左)语言的文本提取支持有限,尤其是处理连写字形、混合拉丁字符的场景时,容易出现字符顺序错乱、字形错误的问题。以下是几种可行的解决方案:

方案1:换用对RTL支持更好的PDF提取库

使用PyMuPDF(fitz)

PyMuPDF对复杂排版的非LTR语言适配性更强,能更准确提取阿拉伯语文本。示例代码:

import csv
import fitz  # PyMuPDF

# 打开PDF文件
pdf_file = fitz.open('1.pdf')
# 获取第一页
first_page = pdf_file[0]
# 提取文本
arabic_text = first_page.get_text()
pdf_file.close()

# 写入CSV
with open('output.csv', 'w', newline='', encoding='utf-8') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerow(['Arabic Text'])
    writer.writerow([arabic_text])

print("提取完成,文本已保存到output.csv")

使用pdfplumber

pdfplumber同样对多语言排版有较好支持,提取逻辑更精细:

import csv
import pdfplumber

with pdfplumber.open('1.pdf') as pdf:
    first_page = pdf.pages[0]
    arabic_text = first_page.extract_text()

# 写入CSV
with open('output.csv', 'w', newline='', encoding='utf-8') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerow(['Arabic Text'])
    writer.writerow([arabic_text])

print("提取完成,文本已保存到output.csv")

方案2:修复提取后的RTL文本(针对仍有问题的场景)

如果换库后仍存在文本顺序或字形错误,可以用arabic_reshaper和python-bidi库来修正:

  1. 先安装依赖:
pip install arabic-reshaper python-bidi
  1. 修正文本的示例代码:
import csv
import fitz
import arabic_reshaper
from bidi.algorithm import get_display

# 提取文本
pdf_file = fitz.open('1.pdf')
arabic_text_raw = pdf_file[0].get_text()
pdf_file.close()

# 修正RTL文本
reshaped_text = arabic_reshaper.reshape(arabic_text_raw)
corrected_text = get_display(reshaped_text)

# 写入CSV
with open('output.csv', 'w', newline='', encoding='utf-8') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerow(['Arabic Text'])
    writer.writerow([corrected_text])

print("提取并修正完成,文本已保存到output.csv")

关键说明

  • 阿拉伯语的复杂字形(比如连写、变体)需要专门的字形重组处理,PyPDF2没有内置这类逻辑,而PyMuPDF/pdfplumber在底层渲染时已经处理了部分RTL排版逻辑。
  • 混合拉丁字符的场景下,python-bidi能正确处理LTR和RTL文本的混合排列顺序,避免字符错乱。

内容的提问来源于stack exchange,提问作者luca sala

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 17:32:10