将列表中的特定项目拆分为两个

时间:2013-04-11 17:57:21

标签: python string list xml-parsing

我正在python中为SVG文件构建XML解析器。它最终将成为步进电机的具体说明。

SVG文件包含“M”,“C”和“L”等命令。路径数据可能如下所示:

[M199.66,0.50C199.6,0.50 ... 0.50Z]

当我提取路径数据时,它是一个项目的列表(这是一个字符串)。我将长字符串分成多个字符串:

[u'M199.6',u'0.50C199.66',u'0.50']

'M,C和L'命令很重要 - 我很难将'0.5C199.6'分成'0.5'和'C199.6',因为它只存在于列表中的某些项目中,而我我想保留C而不是丢弃它。这就是我到目前为止所做的:

for item in path_strings[0]:
    s=string.split(path_strings[0], ',')
    print s
    break
for i in range(len(s)):
    coordinates=string.split(s[i],'C')
    print coordinates
    break

2 个答案:

答案 0 :(得分:1)

您可以尝试将其分解为这样的子串:

whole = "0.5C199.66"
start = whole[0:whole.find("C")]
end = whole[whole.find("C"):]

这应该会给你start == "0.5"end == "C199.66"

或者你可以使用index函数而不是find,当找不到子字符串时会引发ValueError。这样可以轻松确定当前字符串中没有“C”命令。

http://docs.python.org/2/library/string.html#string-functions

答案 1 :(得分:0)

使用正则表达式搜索命令([MCL])。

import re

lst = [u'M199.6', u'0.50C199.66', u'0.50']

for i, j in enumerate(lst):
    m = re.search('(.+?)([MCL].+)', j)
    if m:
        print [m.group(1), m.group(2)] #  = coordinates from your example
        lst[i:i+1] = [m.group(1), m.group(2)] # replace the item in the lst with the splitted thing
        # or do something else with the coordinates, whatever you want.

print lst

将您的列表拆分为:

[u'M199.6', u'0.50', u'C199.66', u'0.50']