我在某些文件中没有得到任何字体名称

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

我不知道为什么它告诉我没有。我已经使用Python docx库来做到这一点,我已经尝试了多次但没有找到任何令人满意的解决方案。

# Function to extract information about 'Abstract heading Font Style' from the document
def abstract_heading_font_style(word_file):
    doc = Document(word_file)
    font_styles = set() 
    
    for paragraph in doc.paragraphs:
        if any(word in paragraph.text for word in ['Abstract', 'ABSTRACT', 'abstract']):
            for run in paragraph.runs:      
                font_styles.add(run.font.name)
                if any(word in paragraph.text for word in ['Abstract', 'ABSTRACT', 'abstract'])and run.bold:      
                        font_styles.add(run.font.name)
            
    return list(font_styles)
python python-docx
1个回答
0
投票

仅当嵌套循环中 run.bold 为 True 时,您才将字体样式添加到 font_styles 中,因此,如果包含“Abstract”的段落中没有粗体运行,它将始终返回 None,因为您没有返回循环之外的任何内容尝试使用下面的代码

from docx import Document


def abstract_heading_font_style(word_file):
    doc = Document(word_file)
    font_styles = set() 
    
    for paragraph in doc.paragraphs:
        if any(word in paragraph.text for word in ['Abstract', 'ABSTRACT', 'abstract']):
            for run in paragraph.runs:
                font_styles.add(run.font.name)
    
    return list(font_styles)

#usage:
word_file = "your_word_file.docx"
abstract_fonts = abstract_heading_font_style(word_file)
print(abstract_fonts)
© www.soinside.com 2019 - 2024. All rights reserved.