【问题标题】:Python - re.split stringPython - re.split 字符串
【发布时间】:2018-03-25 14:46:11
【问题描述】:

我已经寻找解决方案几个小时了。我有一个变量要拆分到嵌套列表中。

points ="""M445,346c28.8,0,56,11.2,76.4,31.6C541.8,398,553,425.2,553,454s-11.2,56-31.6,76.4C501,550.8,473.8,562,445,562
        s-56-11.2-76.4-31.6C348.2,510,337,482.8,337,454s11.2-56,31.6-76.4S416.2,346,445,346 M445,345c-60.2,0-109,48.8-109,109
        s48.8,109,109,109s109-48.8,109-109S505.2,345,445,345L445,345z"""

newPoints = re.split(r'[A-Za-z-]', points)

它是一个多行变量,包含 svg 文件中点的 x 和 y 位置。

模式是它从一个字母开始一个新项目。我想让它订购类似以下的东西。我已经尝试了一些类似上面的选项。邮件问题之一是它不断删除我的分隔符。 :)

[ 
  [ 
     [command],
     [x of p1, y of p1],
     [x of p2, y of p2], 
     [x of p3, y of p3] 
  ] 
]

[ 
[ [M],[445,346] ],
[ [c],[28.8,0],[56,11.2],[76.4,31.6] ]
]

欢迎大家多多指教!

【问题讨论】:

    标签: python regex list split


    【解决方案1】:

    你可以找到字母和浮点数,然后分组:

    import re
    import itertools
    points ="""M445,346c28.8,0,56,11.2,76.4,31.6C541.8,398,553,425.2,553,454s-11.2,56-31.6,76.4C501,550.8,473.8,562,445,562
        s-56-11.2-76.4-31.6C348.2,510,337,482.8,337,454s11.2-56,31.6-76.4S416.2,346,445,346 M445,345c-60.2,0-109,48.8-109,109
        s48.8,109,109,109s109-48.8,109-109S505.2,345,445,345L445,345z"""
    new_points = [list(b) for a, b in itertools.groupby(filter(None, re.findall('[a-zA-Z]+|[\d\.]+', points)), key=lambda x:re.findall('[a-zA-Z]+', x))]
    final_data = [[new_points[i], [int(c) if re.findall('^\d+$', c) else float(c) for c in new_points[i+1]]] for i in range(0, len(new_points)-1, 2)]
    

    输出:

    [[['M'], [445, 346]], [['c'], [28.8, 0, 56, 11.2, 76.4, 31.6]], [['C'], [541.8, 398, 553, 425.2, 553, 454]], [['s'], [11.2, 56, 31.6, 76.4]], [['C'], [501, 550.8, 473.8, 562, 445, 562]], [['s'], [56, 11.2, 76.4, 31.6]], [['C'], [348.2, 510, 337, 482.8, 337, 454]], [['s'], [11.2, 56, 31.6, 76.4]], [['S'], [416.2, 346, 445, 346]], [['M'], [445, 345]], [['c'], [60.2, 0, 109, 48.8, 109, 109]], [['s'], [48.8, 109, 109, 109]], [['s'], [109, 48.8, 109, 109]], [['S'], [505.2, 345, 445, 345]], [['L'], [445, 345]]]
    

    【讨论】:

    • 哇!谢谢!那成功了!我已经更改了“final_data”部分。它遗漏了最后一个(奇数)值。我已将其更改为: final_data = [] for i in range(0, len(new_points),2): try: if new_points[i+1]: final_data.append([new_points[i], new_points[i+ 1]]) 除了 IndexError: final_data.append([new_points[i]])
    • @Tim 很高兴为您提供帮助!
    猜你喜欢
    • 1970-01-01
    • 2013-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    相关资源
    最近更新 更多