从模板中获取密钥 [英] Get keys from template
问题描述
我想获取字符串模板可能在替换中使用的所有可能关键字参数的列表.
除了 re 之外还有其他方法吗?
我想做这样的事情:
text="$one 是一个 $lonely $number."键 = get_keys(文本)#keys = ('one', 'lonely', 'number')
我正在编写一个简单的类似 Mad-lib 的程序,我想使用 string.format 或 模板字符串.我想编写故事"并让我的程序生成用户需要生成的所有关键字"(名词、动词等)的模板文件.我知道我可以用正则表达式做到这一点,但我想知道是否有替代解决方案?我对 string.format 和 string 模板的替代品持开放态度.
我认为会有解决方案,但我没有在快速搜索中遇到它.我确实找到了这个问题,使用 python 反向模板,但这并不是我真正想要的为了.它只是重申这可以通过 re
来完成.
我应该注意到 $$
是 '$' 的转义符,而不是我想要的标记.$$5
应该呈现为$5".
如果可以使用 string.format
,请考虑使用内置类 string.Formatter
有一个 parse()
方法:
有关详细信息,请参阅此处.
I would like to get a list of all possible keyword arguments a string template might use in a substitution.
Is there a way to do this other than re?
I want to do something like this:
text="$one is a $lonely $number."
keys = get_keys(text)
# keys = ('one', 'lonely', 'number')
I'm writing a simple Mad-lib-like program, and I want to perform template substitution with either string.format or Template strings. I'd like to write the 'story' and have my program produce a template file of all the 'keywords' (nouns, verbs, etc.) that a user would need to produce. I know I can do this with regular expressions, but I was wondering if there is an alternative solution? I'm open to alternatives to string.format and string template.
I thought there would be solution to this, but I haven't come across it in a quick search. I did find this question, reverse template with python, but it's not really what I'm looking for. It just reaffirms that this can be done with re
.
EDIT:
I should note that $$
is an escape for '$', and is not a token I want. $$5
should render to "$5".
If it's okay to use string.format
, consider using built-in class string.Formatter
which has a parse()
method:
>>> from string import Formatter
>>> [i[1] for i in Formatter().parse('Hello {1} {foo}') if i[1] is not None]
['1', 'foo']
See here for more details.
这篇关于从模板中获取密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!