[英]Split specific items in list into two
我在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
您可以嘗試將其分成以下子字符串:
whole = "0.5C199.66"
start = whole[0:whole.find("C")]
end = whole[whole.find("C"):]
那應該讓您start == "0.5"
和end == "C199.66"
另外,您可以使用索引函數代替find,當找不到子字符串時會引發ValueError。 這將使您輕松確定當前字符串不存在“ C”命令的好處。
http://docs.python.org/2/library/string.html#string-functions
使用正則表達式搜索命令( [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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.