SyntaxError: prefix 'a' not found in prefix map
SyntaxError: prefix 'a' not found in prefix map
我正在尝试创建一个函数来计算 pptx
文档中的字数。问题是我不知道如何只找到这种标签:
<a:t>Some Text</a:t>
当我尝试:print xmlTree.findall('.//a:t')
,它 returns
SyntaxError: prefix 'a' not found in prefix map
你知道如何让它发挥作用吗?
这是函数:
def get_pptx_word_count(filename):
import xml.etree.ElementTree as ET
import zipfile
z = zipfile.ZipFile(filename)
i=0
wordcount = 0
while True:
i+=1
slidename = 'slide{}.xml'.format(i)
try:
slide = z.read("ppt/slides/{}".format(slidename))
except KeyError:
break
xmlTree = ET.fromstring(slide)
for elem in xmlTree.iter():
if elem.tag=='a:t':
#text = elem.getText
#num = len(text.split(' '))
#wordcount+=num
您需要告诉 ElementTree
您的 XML 命名空间。
参考文献:
- 官方文档 (Python 2.7): 19.7.1.6. Parsing XML with Namespaces
- Whosebug 上的现有答案: Parsing XML with namespace in Python via 'ElementTree'
- ElementTree作者文章: ElementTree: Working with Namespaces and Qualified Names
ElementTree内部指定命名空间的方式是:
{namespace}element
因此,您应该将查询更改为:
print xmlTree.findall('.//{a}t')
编辑:
正如@mxjn 所指出的,如果 a 是前缀而不是 URI,则您需要插入 URI 而不是 a:
print xmlTree.findall('.//{http://tempuri.org/name_space_of_a}t')
或者您可以提供前缀映射:
prefix_map = {"a": "http://tempuri.org/name_space_of_a"}
print xmlTree.findall('.//a:t', prefix_map)
我正在尝试创建一个函数来计算 pptx
文档中的字数。问题是我不知道如何只找到这种标签:
<a:t>Some Text</a:t>
当我尝试:print xmlTree.findall('.//a:t')
,它 returns
SyntaxError: prefix 'a' not found in prefix map
你知道如何让它发挥作用吗?
这是函数:
def get_pptx_word_count(filename):
import xml.etree.ElementTree as ET
import zipfile
z = zipfile.ZipFile(filename)
i=0
wordcount = 0
while True:
i+=1
slidename = 'slide{}.xml'.format(i)
try:
slide = z.read("ppt/slides/{}".format(slidename))
except KeyError:
break
xmlTree = ET.fromstring(slide)
for elem in xmlTree.iter():
if elem.tag=='a:t':
#text = elem.getText
#num = len(text.split(' '))
#wordcount+=num
您需要告诉 ElementTree
您的 XML 命名空间。
参考文献:
- 官方文档 (Python 2.7): 19.7.1.6. Parsing XML with Namespaces
- Whosebug 上的现有答案: Parsing XML with namespace in Python via 'ElementTree'
- ElementTree作者文章: ElementTree: Working with Namespaces and Qualified Names
ElementTree内部指定命名空间的方式是:
{namespace}element
因此,您应该将查询更改为:
print xmlTree.findall('.//{a}t')
编辑:
正如@mxjn 所指出的,如果 a 是前缀而不是 URI,则您需要插入 URI 而不是 a:
print xmlTree.findall('.//{http://tempuri.org/name_space_of_a}t')
或者您可以提供前缀映射:
prefix_map = {"a": "http://tempuri.org/name_space_of_a"}
print xmlTree.findall('.//a:t', prefix_map)