gpt4 book ai didi

使用自定义双括号格式的 Python 模板安全替换

转载 作者:行者123 更新时间:2023-11-28 16:28:39 25 4
gpt4 key购买 nike

我正在尝试用 Python 的模板替换格式为 {{var}} 的变量。

from string import Template

class CustomTemplate(Template):
delimiter = '{{'
pattern = r'''
\{\{(?:
(?P<escaped>\{\{)|
(?P<named>[_a-z][_a-z0-9]*)\}\}|
(?P<braced>[_a-z][_a-z0-9]*)\}\}|
(?P<invalid>)
)
'''

replacement_dict = {
"test": "hello"
}

tpl = '''{
"unaltered": "{{foo}}",
"replaced": "{{test}}"
}'''

a = CustomTemplate(tpl)
b = a.safe_substitute(replacement_dict)

print(b)

输出:

{
"unaltered": "{{foo",
"replaced": "hello"
}

如您所见,{{foo}} 变量(不是替换的一部分)的右括号被砍掉了。我认为这是正则表达式的编写方式(结束 \}\})?

我想用模板解决这个问题,而不是用任何其他外部库。

最佳答案

我不确定你是怎么做到的。在 linux 上,在 python 3.4.3 中(我想我可以使用 2.7 的某些版本)我需要将 tpl 设为一个字符串

tpl = '''
"unaltered": "{{foo}}",
"replaced": "{{test}}"
'''

避免出现类型错误

>>> tpl = '''
... "unaltered": "{{foo}}",
... "replaced": "{{test}}"
... '''
>>> a = CustomTemplate(tpl)
>>> a.template
'\n "unaltered": "{{foo}}",\n "replaced": "{{test}}"\n'
>>> b = a.safe_substitute(replacement_dict)
>>> b
'\n "unaltered": "{{foo}}",\n "replaced": "hello"\n'

当我这样做时,{{foo}} 没有改变。

我试过上面的代码,看起来代码实际上不适用于 python 2.7.6。我会看看是否可以找到一种方法让它与 2.7.6 一起工作,因为这似乎是最近 linux 发行版的常见版本。

更新:

看起来这是 2007 年的一个已知错误。http://bugs.python.org/issue1686据我所知,它在 2010 年应用于 python 3.2,在 2014 年应用于 python 2.7。就让它起作用而言,您可以应用问题 1686 的补丁,或者您可以覆盖类中的 safe_substitute()此补丁的实际源代码 https://hg.python.org/cpython/file/8a98ee6baa1e/Lib/string.py .

此代码适用于 2.7.6 和 3.4.3

from string import Template
class CustomTemplate(Template):
delimiter = '{{'
pattern = r'''
\{\{(?:
(?P<escaped>\{\{)|
(?P<named>[_a-z][_a-z0-9]*)\}\}|
(?P<braced>[_a-z][_a-z0-9]*)\}\}|
(?P<invalid>)
)
'''

def safe_substitute(self, *args, **kws):
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
named = mo.group('named') or mo.group('braced')
if named is not None:
try:
# We use this idiom instead of str() because the latter
# will fail if val is a Unicode containing non-ASCII
return '%s' % (mapping[named],)
except KeyError:
return mo.group()
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
return mo.group()
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template)

replacement_dict = {
"test": "hello"
}

tpl = '''{
"escaped": "{{{{",
"unaltered": "{{foo}}",
"replaced": "{{test}}",
"invalid": "{{az"
}'''

a = CustomTemplate(tpl)
b = a.safe_substitute(replacement_dict)

print (b)

结果:

Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import template
{
"escaped": "{{",
"unaltered": "{{foo}}",
"replaced": "hello",
"invalid": "{{az"
}
>>>

关于使用自定义双括号格式的 Python 模板安全替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34360603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com