某些文件中的字体名称显示为空
我不知道为什么它告诉我结果是None。我使用了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)
1 个回答
-1
你在嵌套循环中只有当 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)