可以使用Python的xml.etree.ElementTree
模塊通過以下步驟刪除XML中的w:ascii
屬性:
import xml.etree.ElementTree as ET# 原始XML片段(需包含命名空間聲明)
xml_str = '''
<w:rPr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:rFonts w:ascii="Times New Roman" w:eastAsia="黑體" w:hAnsi="Times New Roman"/><w:color w:val="auto"/><w:sz w:val="44"/>
</w:rPr>
'''# 注冊命名空間
namespaces = {'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'
}# 解析XML
root = ET.fromstring(xml_str)# 查找所有w:rFonts元素
for r_fonts in root.findall('w:rFonts', namespaces):# 構建完整屬性名(包含命名空間)ascii_attr = '{' + namespaces['w'] + '}ascii'# 刪除屬性if ascii_attr in r_fonts.attrib:del r_fonts.attrib[ascii_attr]# 輸出修改后的XML
ET.indent(root, space=" ", level=0)
print(ET.tostring(root, encoding='unicode'))
修改后的輸出結果:
<w:rPr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:rFonts w:eastAsia="黑體" w:hAnsi="Times New Roman" /><w:color w:val="auto" /><w:sz w:val="44" />
</w:rPr>
關鍵點說明:
-
命名空間處理:
- 使用
namespaces
字典注冊w
前綴對應的URI - 屬性名需要包含完整的命名空間URI(格式:
{uri}localname
)
- 使用
-
屬性操作:
- 通過
r_fonts.attrib
字典訪問屬性 - 使用
del
語句刪除指定屬性
- 通過
-
批量處理:
- 使用
findall
方法查找所有匹配的元素 - 支持處理文檔中多個
<w:rFonts>
標簽的情況
- 使用
在Word文檔中的實際應用:
如果需要修改實際Word文檔中的樣式,建議結合python-docx
庫使用:
from docx import Documentdef remove_ascii_font(doc_path):doc = Document(doc_path)# 遍歷所有段落樣式for style in doc.styles:if style.type == 1: # 段落樣式r_fonts = style.element.xpath('.//w:rFonts', namespaces=namespaces)for elem in r_fonts:ascii_attr = '{' + namespaces['w'] + '}ascii'if ascii_attr in elem.attrib:del elem.attrib[ascii_attr]doc.save('modified.docx')# 使用示例
remove_ascii_font('original.docx')
注意事項:
- 操作前務必備份原始文檔
- Word樣式系統可能包含繼承關系,需要確保修改目標樣式
- 某些樣式可能被鎖定無法修改,需檢查文檔保護設置
- 建議使用
lxml
庫替代標準庫ElementTree以獲得更好的XPath支持
這種方法直接操作XML結構,比通過python-docx的API操作更底層,適合處理復雜樣式修改需求。對于簡單修改,仍推薦優先使用python-docx的標準API。