从.docx文档的xml中提取数据

2024-06-16 09:38:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要提取标签之间的数据,如下所述。另外,如果数据对应于相同的id,我想连接数据

例如,根据下面的XML,两个标记都位于对应于相同id“00F1234A”的选项卡内 因此,需要提取“Hello World”

xml_string="
<w:r w:rsid="00F1234A">     
    <w:rPr> 

    </w:rPr>
    <w:t>Hello</w:t>
</w:r>   


<w:r w:rsid="00F1234A">     
    <w:rPr> 

    </w:rPr>
    <w:t xml:space="preserve">World</w:t>
</w:r>"

目前,我正在使用以下正则表达式在标记之间提取数据

re.findall("<w:t>(.+?)</w:t>",xml_string)

这给了我你好,但不是你好世界

如何连接与相同id(在本例中为“00F1234A”)对应的中的数据


Tags: 数据标记reidhelloworldstringspace
1条回答
网友
1楼 · 发布于 2024-06-16 09:38:31

为了解析它,您需要XML(xmlns: x = "urn:something")中的名称空间

使用etrees提取值,而不是像这样使用正则表达式:

 import xml.etree.ElementTree as ET
#parse XML string
tree = ET.fromstring('xml_string')

#declare namespace dictionary
nsmap = {'w':'http://schemas.openxmlformats.org/wordprocessingml/2006/main'}

tagvalues = []
#loop through all w:t tags and append their values to list
for i in root.findall('.//w:r//w:t', nsmap):
    tagvalues.append(i.text)

#concatenate all values into a string
string  = ''
[string.join(word) for word in tagvalues]

也请查看this post

相关问题 更多 >