开发者

The opposite of string.Template in Python

I know template can work like the following:

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

and y will give me:

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

I am wondering if there is a way to do the reverse of this? something like my made up unpack:

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

and have z return something like:

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

any ideas? should i be using regular expressions instead?

EDIT: If using regular expressions how would i program for the following 3 lines to return the first开发者_Python百科 number and the 6 trailing numbers?

   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"

I tried this on those and couldn't seem to get it working:

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

SOLUTION: Using regular expressions tutorial (thanks 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')

You can also do this to get a dict of the values

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


Regarding your edit, if you're looking to work with regular expressions, I highly recommend looking at a tutorial; without some guidance regular expressions look like incompressible garbage, and even though other people can write your regular expressions for you, you should at least understand what they are doing.

That being said,

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


What you can do is create a class with your custom templating identifier and then use regular expression to identify those identifiers from the objects you create. You wish to create a dictionary to store those identifier value pairs and then in your (custom) methods such as unpack , just give the values of the identifiers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜