Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
118 views
in Technique[技术] by (71.8m points)

python - Get keys from template

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".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...