如何在python中使用模板库

时间:2015-05-13 21:59:14

标签: python

我正在使用内置的python模板库..

from string import Template
feature_names = ['f1','f2']
load_identifiers = ["foo","bar"]
fleh = map(lambda (load_identifier,feature_name):Template("FLATTEN((IsEmpty($load_identifier.\$1) ? null : BagToTuple($load_identifier.\$1))) AS $feature_name ").substitute(load_identifier=load_identifier, feature_name=feature_name), zip(load_identifiers, feature_names))

但是我收到以下错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-177-ddbfd32ef884> in <module>()
----> 1 fleh = map(lambda (load_identifier,feature_name):Template("FLATTEN((IsEmpty($load_identifier.\$1) ? null : BagToTuple($load_identifier.\$1))) AS $feature_name ").substitute(load_identifier=load_identifier, feature_name=feature_name), zip(load_identifiers, feature_names))

<ipython-input-177-ddbfd32ef884> in <lambda>((load_identifier, feature_name))
----> 1 fleh = map(lambda (load_identifier,feature_name):Template("FLATTEN((IsEmpty($load_identifier.\$1) ? null : BagToTuple($load_identifier.\$1))) AS $feature_name ").substitute(load_identifier=load_identifier, feature_name=feature_name), zip(load_identifiers, feature_names))

/anaconda/lib/python2.7/string.pyc in substitute(self, *args, **kws)
    170             raise ValueError('Unrecognized named group in pattern',
    171                              self.pattern)
--> 172         return self.pattern.sub(convert, self.template)
    173 
    174     def safe_substitute(self, *args, **kws):

/anaconda/lib/python2.7/string.pyc in convert(mo)
    167                 return self.delimiter
    168             if mo.group('invalid') is not None:
--> 169                 self._invalid(mo)
    170             raise ValueError('Unrecognized named group in pattern',
    171                              self.pattern)

/anaconda/lib/python2.7/string.pyc in _invalid(self, mo)
    144             lineno = len(lines)
    145         raise ValueError('Invalid placeholder in string: line %d, col %d' %
--> 146                          (lineno, colno))
    147 
    148     def substitute(self, *args, **kws):

ValueError: Invalid placeholder in string: line 1, col 36

2 个答案:

答案 0 :(得分:2)

OP在这里..回答问题: 模式中有一个'$',需要转义,因为'$ var'用于变量替换。 所以,

fleh = map(lambda (load_identifier,feature_name):Template("FLATTEN((IsEmpty($load_identifier.\$$1) ? null : BagToTuple($load_identifier.\$$1))) AS $feature_name ").substitute(load_identifier=load_identifier, feature_name=feature_name), zip(load_identifiers, feature_names))

作品

答案 1 :(得分:0)

不需要模板导入。

feature_names = ['f1','f2']
load_identifiers = ["foo","bar"]
ts = "FLATTEN((IsEmpty(%(load_identifier)s.$1) ? null : BagToTuple(%(load_identifier)s.$1))) AS %(feature_name)s"

fleh = [ts % d for d in [{'feature_name': fn, 'load_identifier': li} 
    for fn, li in zip(feature_names, load_identifiers)]]