获取Python中String Template中所有标识符的函数

3

在Python的标准库字符串模板中,是否有一个函数可以获取所有标识符的列表?

比如,以下是一个xml文件:

<Text>Question ${PrimaryKey}:</Text>
<Text>Cheat: ${orientation}</Text>

该函数将返回类似于PrimaryKey,orientation的内容。

所以你想在一个XML文件中搜索所有${something}的出现次数? - geckon
2个回答

5

您可以使用string.Formatter.parse

from string import Formatter

s="""<Text>Question ${PrimaryKey}:</Text>
<Text>Cheat: ${orientation}</Text>"""


print([ele[1] for ele in Formatter().parse(s) if ele[1]])
['PrimaryKey', 'orientation']

这个有效!那么是方括号围绕短语生成ele[1]列表吗? - Megool
@YunChan,它提取第二个元素,即占位符名称。如果您print(list(Formatter().parse(s))),您将看到它返回不同元素的元组,其中包含 [('<Text>Question $', 'PrimaryKey', '', None), (':</Text>\n<Text>Cheat: $', 'orientation', '', None), ('</Text>', None, None, None)] - Padraic Cunningham

1

Python 3.11+

一个叫做 get_identifiers() 的方法应该会有所帮助

from string import Template

s="""<Text>Question ${PrimaryKey}:</Text>
<Text>Cheat: ${orientation}</Text>"""
temp = Template(s)
print(temp.get_identifiers())

返回

['PrimaryKey', 'orientation']

否则上面的解决方案很有效。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接