Skip to main content
 首页 » 编程设计

python之如何在python中使用模板库

2024年10月25日12webabcd

我正在使用内置的 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 

请您参考如下方法:

OP here.. 回答问题: 模式中有一个“$”。需要转义,因为“$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)) 

作品