0

我正在为 SVG 文件在 python 中构建 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
4

2 回答 2

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

于 2013-04-11T18:08:55.373 回答
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']
于 2013-04-11T18:55:54.337 回答