如何从参数化字符串中获取参数名称?

How to get parameter names from a parametrized string?

我想要的是:

param_str = "I like $thing_I_like and dislike $thing_I_dislike. What does $person_I_like like?"
get_params(param_str)  # -> ("thing_I_like", "thing_I_dislike", "person_I_like")

我已经看过 string.Template,它只做替换。

是否有标准库方法可以做到这一点?因为在正则表达式的情况下,必须检查 $smt 是否实际上是一个有效的 Python 变量名等等。

string.Template 或其子 class 之一存储编译后的正则表达式,用于查找要替换的标识符作为 pattern class 属性。因此你可以这样做:

>>> from string import Template
>>> s = "I like $thing_I_like and dislike $thing_I_dislike. What does $person_I_like like?"
>>> Template.pattern.findall(s)
[('', 'thing_I_like', '', ''), ('', 'thing_I_dislike', '', ''), ('', 'person_I_like', '', '')]

结果中的组是:

  • escaped(例如 $$ -> "$");
  • named(例如 $identifier -> "identifier");
  • braced(例如 ${noun}ification -> "noun");或
  • invalid“任何其他定界符模式(通常是单个定界符)”,例如 $ -> "")。

因此,为了您的目的,您可能需要:

>>> [
...     named or braced
...     for escaped, named, braced, invalid in Template.pattern.findall(s)
...     if named or braced
... ]
['thing_I_like', 'thing_I_dislike', 'person_I_like']