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

PyPDF2:如何在访问者函数中访问fontDict对象的键值

解决PyPDF2中DictionaryObject的键值访问问题

方法1:使用自带的get()方法访问

PyPDF2的DictionaryObject是自定义字典类型,支持用get()方法安全获取键值,和普通字典用法一致,还能避免键不存在时抛出异常:

from PyPDF2 import PdfReader

reader = PdfReader("E:\Programming\nlp\documents_to_search\GeoBase_NHNC1_Data_Model_UML_EN.pdf")
page = reader.pages[0]

def visitor_body(text, cm, tm, fontDict, fontSize):
    # 第二个参数为键不存在时的默认值
    base_font = fontDict.get('/BaseFont', '未知字体')
    print(base_font)
        
page.extract_text(visitor_text=visitor_body)

方法2:转换为普通Python字典

如果更习惯普通字典的操作逻辑,可以直接把DictionaryObject转换成普通dict:

from PyPDF2 import PdfReader

reader = PdfReader("E:\Programming\nlp\documents_to_search\GeoBase_NHNC1_Data_Model_UML_EN.pdf")
page = reader.pages[0]

def visitor_body(text, cm, tm, fontDict, fontSize):
    normal_dict = dict(fontDict)
    print(normal_dict['/BaseFont'])
        
page.extract_text(visitor_text=visitor_body)

额外提示:筛选特定字体粗细/样式的文本

要提取符合特定粗细或样式的文本,可通过/BaseFont名称(通常含Bold/Italic等标识)或/FontWeight值判断:

def visitor_body(text, cm, tm, fontDict, fontSize):
    base_font = fontDict.get('/BaseFont', '')
    # 筛选粗体文本
    if 'Bold' in base_font:
        print(f"粗体文本:{text}")
    # 通过字体权重值筛选(≥700通常为粗体)
    font_weight = fontDict.get('/FontWeight', 400)
    if int(font_weight) >= 700:
        print(f"粗体文本(权重≥700):{text}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 14:00:57