如何从目录中批量提取SVG文件的d属性?
我来给你几个实用的解决方案,分别用你偏好的JavaScript(Node.js环境)、Python和bash实现,都能高效遍历目录里的SVG文件并提取path的d属性~
JavaScript(Node.js)方案
这个方案用fs模块遍历目录,搭配cheerio(类jQuery的DOM解析库)解析SVG——比起正则表达式,用XML解析器能更稳妥地处理SVG的结构,避免边缘情况出错。
步骤:
- 先初始化项目并安装依赖:
npm init -y npm install cheerio fs-extra
- 编写代码(比如命名为
extract-svg-d.js):
const fs = require('fs-extra'); const cheerio = require('cheerio'); const path = require('path'); // 替换成你的SVG目录路径 const SVG_DIR = './svg-icons'; async function extractPathD() { try { // 读取目录下所有文件 const files = await fs.readdir(SVG_DIR); // 过滤出.svg后缀的文件 const svgFiles = files.filter(file => file.toLowerCase().endsWith('.svg')); for (const fileName of svgFiles) { const filePath = path.join(SVG_DIR, fileName); const svgContent = await fs.readFile(filePath, 'utf8'); // 开启XML模式解析SVG,适配XML结构的命名空间 const $ = cheerio.load(svgContent, { xmlMode: true }); // 提取所有path元素的d属性 const dAttributes = $('path').map((i, el) => $(el).attr('d')).get(); // 输出结果,你可以改成写入文件或其他自定义处理 console.log(`=== ${fileName} ===`); dAttributes.forEach((d, index) => { console.log(`Path ${index + 1}: ${d}`); }); console.log('\n'); } } catch (err) { console.error('处理出错:', err); } } extractPathD();
Python方案
Python用标准库的xml.etree.ElementTree解析SVG,无需额外安装依赖,用os模块遍历目录即可。重点是要指定SVG的命名空间,不然会找不到path元素。
代码示例(命名为extract_svg_d.py):
import os import xml.etree.ElementTree as ET # 替换成你的SVG目录路径 SVG_DIR = './svg-icons' # SVG的官方命名空间,必须指定才能匹配到path元素 SVG_NAMESPACE = {'svg': 'http://www.w3.org/2000/svg'} def extract_path_d(): # 遍历目录下所有子目录和文件 for root, dirs, files in os.walk(SVG_DIR): for file in files: if file.lower().endswith('.svg'): file_path = os.path.join(root, file) try: tree = ET.parse(file_path) root_elem = tree.getroot() # 查找所有path元素,带上命名空间前缀 paths = root_elem.findall('.//svg:path', SVG_NAMESPACE) print(f'=== {file} ===') for idx, path in enumerate(paths, 1): d_attr = path.get('d') if d_attr: print(f'Path {idx}: {d_attr}') print('\n') except Exception as e: print(f'处理文件{file}出错: {e}') if __name__ == '__main__': extract_path_d()
Bash方案
如果不想写脚本,用bash命令就能快速搞定,适合Linux/macOS环境(xmllint是大部分系统预装的工具),比grep更准确,能避免误匹配注释或其他文本里的d字符。
命令示例:
# 替换成你的SVG目录路径 SVG_DIR="./svg-icons" # 遍历所有SVG文件,提取path的d属性 find "$SVG_DIR" -type f -iname "*.svg" | while read -r file; do echo "=== $(basename "$file") ===" # 用xmllint解析XML,提取d属性,再用sed清理格式 xmllint --xpath '//svg:path/@d' --namespace "svg=http://www.w3.org/2000/svg" "$file" 2>/dev/null | sed 's/d="//g; s/"//g' echo -e "\n" done
内容的提问来源于stack exchange,提问作者Fernando Martz
相关产品推荐
相关产品推荐

