Python中string.Template的反义词是什么

3 投票
3 回答
1026 浏览
提问于 2025-04-16 19:48

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

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

然后 y 会给我:

"  Coordinates;     23;108;655;\n"

我在想有没有办法做到这个的反向操作?类似我自己编的一个解包方法:

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

然后让 z 返回一些像这样的内容:

["23","108","655"]

有什么想法吗?我是不是应该用正则表达式来处理?

编辑:如果使用正则表达式,我该如何编写代码来让以下三行返回第一个数字和后面六个数字?

   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"

我尝试过这些,但似乎没有成功:

>>> re.match('(\d+);  Coord   ;(\d+);(\d+);(\d+);(\d+);(\d+);(\d+)',a).groups()

解决方案:使用正则表达式 教程(感谢 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')]

3 个回答

0

你可以创建一个类,里面用你自己定义的模板标识符。然后,使用正则表达式来从你创建的对象中找到这些标识符。接着,你可以建立一个字典,用来存储这些标识符和它们对应的值。在你自己定义的方法,比如说 unpack 中,只需要提供这些标识符的值就可以了。

5
>>> import re
>>> y="  Coordinates;     23;108;655;\n"
>>> re.match("  Coordinates;     (\d+);(\d+);(\d+);\n", y).groups()
('23', '108', '655')
>>> re.match("  Coordinates;     (?P<o1>\d+);(?P<o2>\d+);(?P<o3>\d+);\n", y).groupdict()
{'o3': '655', 'o2': '108', 'o1': '23'}

你也可以这样做来获取一个包含值的字典。

2

关于你的修改,如果你想使用正则表达式,我强烈建议你看看一个教程;因为没有一些指导,正则表达式看起来就像是无法理解的垃圾。即使别人可以为你写正则表达式,你至少也应该明白他们在做什么。

话说回来,

>>> re.match(r"\D*(\d+)\D+([\d\.]+)\D+([\d\.]+)\D+(\d+)\D+(\d+)\D+(\d+)\D+(\d+)", 
             "   123;  Coord   ;  19.1335;   3.5010;  1; 3; 8; 4").groups()
('123', '19.1335', '3.5010', '1', '3', '8', '4')

撰写回答