【发布时间】:2021-06-26 04:58:58
【问题描述】:
我想用 python 编写一个程序来检查 MS Word 文件 (.docx) 的一些属性,例如边距、字体名称和字体大小。 (在继续之前,我应该注意,老实说,我不知道我在做什么)
对于字体部分,我遇到了真正的问题:
根据:
https://python-docx.readthedocs.io/en/latest/user/styles-understanding.html
“一个样式可以从另一个样式继承属性,有点类似于级联样式表 (CSS) 的工作方式。 使用 base_style 属性指定继承。通过将一种风格建立在另一种风格上,可以形成任意深度的继承层次结构。 没有基本样式的样式会从文档默认值继承属性。”
所以我尝试了这段代码:
d = Document('1.docx')
d_styles = d.styles
for st in d_styles:
if st.name != "No List": #Ignoring The Numbering Style
print(st.type, st.name, st.base_style)
#print(dir(st.base_style), '\n') there is no such thing as font in dir(st.base_style)
st.base_style 返回“无”
因此基于“没有基本样式的样式从document defaults 继承属性”,答案应该在这部分。但我不知道如何到达。
以下代码也返回“无”:
for st in d_styles:
if st.name != "No List": #Ignoring The Numbering Style
print(st.font.name)
#Outputs: None
for para in d.paragraphs:
for r in para.runs:
print (r.font.name)
#Outputs: None
for para in d.paragraphs:
print(para.style.font.name)
#Outputs: None
我使用过这些来源:
https://python-docx.readthedocs.io/en/latest/api/style.html
https://python-docx.readthedocs.io/en/latest/user/styles-understanding.html
编辑:
我尝试将样式对象作为字典来处理:
for key, value in styles.items() :
print (key, value)
#ERROR: 'Styles' object has no attribute 'items'
print(styles.items())
#ERROR: 'Styles' object has no attribute 'items'
print(styles.keys())
#ERROR: 'Styles' object has no attribute 'keys'
print(styles.values())
#ERROR: 'Styles' object has no attribute 'values'
即使这段代码也返回 None:
style = d.styles['Normal']
f = style.font
print(f.name)
【问题讨论】:
-
我建议您查看文档的 XML 并查看为您提供的提示。归根结底,
python-docx只是底层 XML 文档的用户界面。您可以从print(d.styles["Normal"]._element.xml)开始。如果您在那里没有找到任何字体信息,这将解释为 font.name 获取None。 -
非常感谢您的帮助。不,我找不到任何字体信息,除非我遗漏了什么:
-
xmlns:w16cid="schemas.microsoft.com/office/word/2016/wordml/cid" xmlns:w16="schemas.microsoft.com/office/word/2018/wordml" xmlns:w16sdtdh="schemas.microsoft.com/office/word/2020/wordml/sdtdatahash" xmlns:w16se="schemas.microsoft.com/office/word/2015/wordml/symex" w:type="paragraph " w:default="1" w:styleId="Normal">
-
好的,所以我希望这会退回到文档默认值。我不知道确切的定义在哪里,但我不相信有任何 API 支持在
python-docx中获取或设置它。 -
这个问题有更新吗?对于段落.style.font.name 和大小,我也没有得到任何结果。但是,我可以保留文本和样式名称。这与库中的错误有关吗?我用的是最新版本。
标签: python python-3.x python-docx