extracting keywords from %(keyword)s-based templates
Thomas Weholt
thomas at gatsoft.no
Fri Aug 31 07:14:41 EDT 2001
Sorry for that stupid subject, but ...
Take this piece of code :
def parse(s):
keywords = []
dict = {}
while 1:
try:
str(s % dict)
break
except KeyError, e:
keywords.append(str(e))
dict[str(e)] = ''
except:
raise "Bad format-chars in input-string. Use
'%(keyword)s'-format only." # things like %d etc. not supported. Tips
wanted!!!
return keywords
if __name__ == '__main__':
# define a template s :
s = """
Hello %(somebody)s,
How's the weather in %(someplace)s?
Best regards,
%(me)s
"""
print parse(s)
# output is
['somebody', 'someplace', 'me']
The object is to extract all keywords used in a template. Is there a quicker
way, possibly using regular expressions?
This also just traps %(keyword)s-format. How do I trap stuff like %d etc. ??
Thomas
More information about the Python-list
mailing list