我正在编写一个程序,将标准SVG路径转换为Raphael.js友好格式。
路径数据的格式为

d="M 62.678745,
   259.31235 L 63.560745,
   258.43135 L 64.220745,
   257.99135 L 64.439745,
   258.43135 L 64.000745
     ...
     ...
   "

我想做的是先去掉小数,然后去掉空白。最终结果应采用以下格式
d="M62,
   259L63,
   258L64,
   257L64,
   258L64
     ...
     ...
   "

我有大约2000条这样的路径来解析并转换成JSON文件。
到目前为止我所做的是
from bs4 import BeautifulSoup

svg = open("/path/to/file.svg", "r").read()
soup = BeautifulSoup(svg)
paths = soup.findAll("path")

raphael = []

for p in paths:
  splitData = p['d'].split(",")
  tempList = []

    for s in splitData:
      #strip decimals from string
      #don't know how to do this

      #remove whitespace
      s.replace(" ", "")

      #add to templist
      tempList.append(s + ", ")

    tempList[-1].replace(", ", "")
    raphael.append(tempList)

最佳答案

试试这个:

import re
from bs4 import BeautifulSoup

svg = open("/path/to/file.svg", "r").read()
soup = BeautifulSoup(svg)
paths = soup.findAll("path")

raphael = []

for p in paths:
    splitData = p['d'].split(",")
    for line in splitData:
        # Remove ".000000" part
        line = re.sub("\.\d*", "", line)
        line = line.replace(" ", "")
        raphael.append(line)

d = ",\n".join(raphael)

关于python - Python-删除字符,然后加入字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17515099/

10-09 18:09
查看更多