Python提取字符串模板中的变量

2024-06-26 02:01:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我熟悉使用Templates将变量插入字符串的能力,如下所示:

Template('value is between $min and $max').substitute(min=5, max=10)

我现在想知道的是是否有可能做相反的事情。我想获取一个字符串,并使用模板从中提取值,这样我就有了一些包含提取值的数据结构(最好只是命名变量,但dict很好)。例如:

>>> string = 'value is between 5 and 10'
>>> d = Backwards_template('value is between $min and $max').extract(string)
>>> print d
{'min': '5', 'max':'10'}

这可能吗?


Tags: and字符串模板数据结构stringisvaluetemplate
3条回答

这叫做regular expressions

import re
string = 'value is between 5 and 10'
m = re.match(r'value is between (.*) and (.*)', string)
print(m.group(1), m.group(2))

输出:

5 10

更新1。可以将名称指定给组:

m = re.match(r'value is between (?P<min>.*) and (?P<max>.*)', string)
print(m.group('min'), m.group('max'))

但是这个特性并不经常被使用,因为在一个更重要的方面通常会有足够的问题:如何准确地捕获您想要的内容(在这个并不重要的特殊情况下,但即使在这里:如果字符串是value is between 1 and 2 and 3——应该接受字符串,以及minmax)是什么。


更新2。与生成精确的正则表达式相比,有时更容易组合正则表达式和“正则”代码,如下所示:

m = re.match(r'value is between (?P<min>.*) and (?P<max>.*)', string)
try:
    value_min = float(m.group('min'))
    value_max = float(m.group('max'))
except (AttributeError, ValueError):  # no match or failed conversion
    value_min = None
    value_max = None

当您的文本由多个要处理的块(如不同类型的引号中的短语)组成时,这种组合方法尤其值得记住:在复杂的情况下,定义单个regex来处理块的分隔符和内容比定义几个步骤(如text.split())、可选的块合并和独立的处理每个块(使用正则表达式和其他方法)。

不可能完全逆转替换。问题是有些字符串是不明确的,例如

value is between 5 and 7 and 10

有两种可能的解决方案:min = "5", max = "7 and 10"min = "5 and 7", max = "10"

但是,您可以使用regex获得有用的结果:

import re

string = 'value is between 5 and 10'
template= 'value is between $min and $max'

pattern= re.escape(template)
pattern= re.sub(r'\\\$(\w+)', r'(?P<\1>.*)', pattern)
match= re.match(pattern, string)
print(match.groupdict()) # output: {'max': '10', 'min': '5'}

行为驱动开发的^{} module提供了一些不同的机制来指定和parsing templates.

根据模板的复杂性和应用程序的其他需求,您可能会发现其中一个最有用。(另外,你可以窃取他们预先编写的代码。)

相关问题 更多 >