与Python中的string.Template相反

Sym*_*mon 3 python regex string templates

我知道模板可以像下面这样工作:

x = Template("  Coordinates;     $o1;$o2;$o3;\n")
y = x.substitute(o1 = 23, o2 = 108, o3 = 655)
Run Code Online (Sandbox Code Playgroud)

你会给我:

"  Coordinates;     23;108;655;\n"
Run Code Online (Sandbox Code Playgroud)

我想知道是否有办法逆转这个?像我打包的东西解压缩:

x = Template("  Coordinates;     $o1;$o2;$o3;\n")
y = "  Coordinates;     23;108;655;\n"
z = x.unpack(y)
Run Code Online (Sandbox Code Playgroud)

并让z返回类似的东西:

["23","108","655"]
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?我应该使用正则表达式吗?

编辑:如果使用正则表达式,我将如何编程以下3行返回第一个数字和6个尾随数字?

   a = "   123;  Coord   ;  19.1335;   3.5010;  1; 3; 8; 4"
   b = "    17;  Coord   ;  15.2940;  13.5010;  3; 1; 8; 8"
   c = "     5;  Coord   ;  19.1345;   0.6200;  1; 1; 7; 8"
Run Code Online (Sandbox Code Playgroud)

我尝试了这些,似乎无法让它工作:

>>> re.match('(\d+);  Coord   ;(\d+);(\d+);(\d+);(\d+);(\d+);(\d+)',a).groups()
Run Code Online (Sandbox Code Playgroud)

解决方案:使用正则表达式教程(感谢ironchefpython):

>>> import re
>>> text = """
       123;  Coord   ;  19.1335;   3.5010;  1; 3; 8; 4
        17;  Coord   ;  15.2940;  13.5010;  3; 1; 8; 8
         5;  Coord   ;  19.1345;   0.6200;  1; 1; 7; 8
    """
>>> coord = re.compile("\D*(\d+)\D+([\d\.]+)\D+([\d\.]+)\D+(\d+)\D+(\d+)\D+(\d+)\D+(\d+)")
>>> coord.findall(text)
[('123','19.1335','3.5010','1','3','8','4'),('17','15.2940','13.5010','3','1','8','8'),('5','19.1345','0.6200','1','1','7','8')]
Run Code Online (Sandbox Code Playgroud)

Joh*_*ooy 5

>>> import re
>>> y="  Coordinates;     23;108;655;\n"
>>> re.match("  Coordinates;     (\d+);(\d+);(\d+);\n", y).groups()
('23', '108', '655')
Run Code Online (Sandbox Code Playgroud)

您也可以这样做以获得值的字典

>>> re.match("  Coordinates;     (?P<o1>\d+);(?P<o2>\d+);(?P<o3>\d+);\n", y).groupdict()
{'o3': '655', 'o2': '108', 'o1': '23'}
Run Code Online (Sandbox Code Playgroud)