import re
from urllib.request import urlopen
SVG_R = r'(?:<\?xml\b[^>]*>[^<]*)?(?:<! .*? >[^<]*)*(?:<svg|<!DOCTYPE svg)\b'
SVG_RE = re.compile(SVG_R, re.DOTALL)
# an example SVG file:
f = urlopen("https://upload.wikimedia.org/wikipedia/commons/1/17/Yin_yang.svg")
file_contents = f.read().decode('latin_1') # avoid any conversion exception
is_svg = SVG_RE.match(file_contents) is not None
print(['NOT SVG', 'SVG'][is_svg]) # prints SVG
可能的优化是仅读取和/或解码前N个字节。确定N的问题在于
<svg
或<!DOCTYPE svg
之前可能有非常长的注释该正则表达式已在我的Mac上使用32120个SVG文件进行了验证
相关问题 更多 >
编程相关推荐