我试图通过修改描绘美国所有县的SVG 地图来生成等值线地图。基本方法由Flowing Data捕获。由于 SVG 基本上只是 XML,因此该方法利用了BeautifulSoup解析器。
问题是,解析器不会捕获path
SVG 文件中的所有元素。以下仅捕获了 149 条路径(超过 3000 条):
#Open SVG file
svg=open(shp_dir+'USA_Counties_with_FIPS_and_names.svg','r').read()
#Parse SVG
soup = BeautifulSoup(svg, selfClosingTags=['defs','sodipodi:namedview'])
#Identify counties
paths = soup.findAll('path')
len(paths)
但是,我知道,物理检查以及ElementTree方法使用以下例程捕获 3,143 条路径这一事实都存在更多:
#Parse SVG
tree = ET.parse(shp_dir+'USA_Counties_with_FIPS_and_names.svg')
#Capture element
root = tree.getroot()
#Compile list of IDs from file
ids=[]
for child in root:
if 'path' in child.tag:
ids.append(child.attrib['id'])
len(ids)
我还没有弄清楚如何以ElementTree
一种不完全混乱的方式从对象中写入。
#Define style template string
style='font-size:12px;fill-rule:nonzero;stroke:#FFFFFF;stroke-opacity:1;'+\
'stroke-width:0.1;stroke-miterlimit:4;stroke-dasharray:none;'+\
'stroke-linecap:butt;marker-start:none;stroke-linejoin:bevel;fill:'
#For each path...
for child in root:
#...if it is a path....
if 'path' in child.tag:
try:
#...update the style to the new string with a county-specific color...
child.attrib['style']=style+col_map[child.attrib['id']]
except:
#...if it's not a county we have in the ACS, leave it alone
child.attrib['style']=style+'#d0d0d0'+'\n'
#Write modified SVG to disk
tree.write(shp_dir+'mhv_by_cty.svg')
上面的修改/写入例程产生了这个怪物:
我的主要问题是:为什么 BeautifulSoup 未能捕获所有path
标签?其次,为什么用ElementTree
对象修改的图像会进行所有的课外活动?任何建议将不胜感激。