gpt4 book ai didi

python - 与 Python 中的 string.Template 相反

转载 作者:太空宇宙 更新时间:2023-11-03 13:23:21 25 4
gpt4 key购买 nike

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

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

你会给我:

"  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"]

有什么想法吗?我应该改用正则表达式吗?

编辑:如果使用正则表达式,我将如何为以下 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"

我在那些上试过了,但似乎无法正常工作:

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

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

最佳答案

>>> 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'}

关于python - 与 Python 中的 string.Template 相反,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6391699/

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