本文整理汇总了Python中shapefile.Reader.shapes方法的典型用法代码示例。如果您正苦于以下问题:Python Reader.shapes方法的具体用法?Python Reader.shapes怎么用?Python Reader.shapes使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类shapefile.Reader
的用法示例。
在下文中一共展示了Reader.shapes方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: merge_shapes
# 需要导入模块: from shapefile import Reader [as 别名]
# 或者: from shapefile.Reader import shapes [as 别名]
def merge_shapes(inputfile,
outputfile = None,
overwrite = False,
verbose = True,
vverbose = False,
):
"""
Merges all the shapes in a shapefile into a single shape.
"""
if outputfile is None: output = '{}/merged'.format(os.getcwd())
if os.path.isfile(outputfile + '.shp') and not overwrite:
if verbose:
print('combined watershed shapefile {} exists'.format(outputfile))
return
if verbose: print('combining shapes from {}\n'.format(inputfile) +
'this may take a while...\n')
# start by copying the projection files
shutil.copy(inputfile + '.prj', outputfile + '.prj')
# load the catchment and flowline shapefiles
r = Reader(inputfile, shapeType = 5)
try:
combined = combine_shapes(r.shapes(), verbose = vverbose)
except:
print('error: unable to combine shapes')
raise
# create the new file with the merged shapes
w = Writer(shapeType = 5)
w.poly(shapeType = 5, parts = [combined])
# copy the fields from the original and then the first record; note this
# can be adapted as needed
for field in r.fields: w.field(*field)
w.record(*r.record(0))
w.save(outputfile)
if verbose:
its = inputfile, outputfile
print('successfully combined shapes from {} to {}\n'.format(*its))
示例2: extract_raw
# 需要导入模块: from shapefile import Reader [as 别名]
# 或者: from shapefile.Reader import shapes [as 别名]
def extract_raw(source, destination, HUC8, plot = True, save = True,
verbose = True):
"""Extracts the grid data for the HUC8."""
# make a new directory for the HUC8
d = '{}/{}/NRCM'.format(destination, HUC8)
if not os.path.isdir(d): os.mkdir(d)
# make a "raw directory" for the unaltered info
raw = '{}/raw'.format(d)
if not os.path.isdir(raw):
os.mkdir(raw)
if verbose: print('extracting NRCM predictions...\n')
# use the boundary file to find the bounding box for the grid points
boundaryfile = '{0}/{1}/{1}boundaries'.format(destination, HUC8)
subbasinfile = '{0}/{1}/{1}subbasins'.format(destination, HUC8)
space = 0.1
sf = Reader(boundaryfile)
bbox = get_boundaries(sf.shapes(), space = space)
xmin, ymin, xmax, ymax = bbox
if verbose and not os.path.isdir(raw):
print('bounding box =', xmin, ymin, xmax, ymax, '\n')
lats, lons = [], []
for f in os.listdir(source):
i = f.index('_')
lon = float(f[:i])
lat = float(f[i+1:])
if inside_box([xmin, ymin], [xmax, ymax], [lon, lat]):
lats.append(lat)
lons.append(lon)
if not os.path.isfile('{}/{}'.format(raw, f)):
shutil.copy('{}/{}'.format(source, f), '{}/{}'.format(raw, f))
if plot:
if save: output = '{}/gridpoints'.format(d)
else: output = None
if not os.path.isfile(output):
plot_NRCM(lons, lats, bfile = boundaryfile, sfile = subbasinfile,
output = output, show = False)
示例3: plot_NRCM
# 需要导入模块: from shapefile import Reader [as 别名]
# 或者: from shapefile.Reader import shapes [as 别名]
def plot_NRCM(lons, lats, bfile = None, sfile = None, space = 0.05,
show = False, output = None):
fig = pyplot.figure()
sub = fig.add_subplot(111, aspect = 'equal')
sub.set_title('Nested Regional Climate Model Grid Points')
sub.scatter(lons, lats, marker = '+', c = 'r', s = 40)
if bfile is not None:
sf = Reader(bfile)
boundary = sf.shape(0).points
sub.add_patch(make_patch(boundary, (1, 0, 0, 0), width = 1.2))
if sfile is not None:
sf = Reader(sfile)
for s in sf.shapes():
boundary = s.points
sub.add_patch(make_patch(boundary, (1, 0, 0, 0), width = 0.2))
sub.set_xlabel('Longitude, Decimal Degrees', size = 13)
sub.set_ylabel('Latitude, Decimal Degrees', size = 13)
xmin, ymin, xmax, ymax = get_boundaries(sf.shapes(), space = space)
pyplot.xlim([xmin, xmax])
pyplot.ylim([ymin, ymax])
if output is not None: pyplot.savefig(output)
if show: pyplot.show()
pyplot.clf()
pyplot.close()
示例4: plot_gage_subbasin
# 需要导入模块: from shapefile import Reader [as 别名]
# 或者: from shapefile.Reader import shapes [as 别名]
def plot_gage_subbasin(self, hspfmodel, folder):
"""Makes a plot of the subbasin area."""
subbasinfile = '{}/subbasins'.format(folder)
boundaryfile = '{}/boundary'.format(folder)
flowfile = '{}/flowlines'.format(folder)
combinedfile = '{}/combined'.format(folder)
watershedplot = '{}/watershed.png'.format(folder)
# make a shapefile of the subbasins for the watershed
f = '{0}/{1}/{1}subbasins'.format(self.directory, self.HUC8)
for out in (subbasinfile, boundaryfile, flowfile, combinedfile):
if not os.path.isfile(out + '.prj'):
shutil.copy(f + '.prj', out + '.prj')
if not os.path.isfile(subbasinfile + '.shp'):
subshapes = []
subrecords = []
for subbasin in hspfmodel.subbasins:
f = '{0}/{1}/{2}/combined'.format(self.directory, self.HUC8,
subbasin)
s = Reader(f, shapeType = 5)
subshapes.append(s.shape(0).points)
subrecords.append(s.record(0))
w = Writer(shapeType = 5)
for field in s.fields: w.field(*field)
for record in subrecords: w.record(*record)
for shape in subshapes: w.poly(shapeType = 5, parts = [shape])
w.save(subbasinfile)
if not os.path.isfile(combinedfile + '.shp'):
fshapes = []
frecords = []
for subbasin in hspfmodel.subbasins:
f = '{0}/{1}/{2}/combined_flowline'.format(self.directory,
self.HUC8,
subbasin)
r = Reader(f, shapeType = 3)
fshapes.append(r.shape(0).points)
frecords.append(r.record(0))
w = Writer(shapeType = 3)
for field in r.fields: w.field(*field)
for record in frecords: w.record(*record)
for shape in fshapes: w.poly(shapeType = 3, parts = [shape])
w.save(combinedfile)
# merge the shapes into a watershed
if not os.path.exists(boundaryfile + '.shp'):
merge_shapes(subbasinfile, outputfile = boundaryfile)
# make a flowline file for the subbasins for the watershed
if not os.path.isfile(flowfile + '.shp'):
shapes = []
records = []
for subbasin in hspfmodel.subbasins:
f = '{0}/{1}/{2}/flowlines'.format(self.directory,
self.HUC8, subbasin)
r = Reader(f, shapeType = 3)
for shape in r.shapes(): shapes.append(shape.points)
for record in r.records(): records.append(record)
w = Writer(shapeType = 3)
for field in r.fields: w.field(*field)
for record in records: w.record(*record)
for shape in shapes: w.poly(shapeType = 3, parts = [shape])
w.save(flowfile)
if not os.path.isfile(watershedplot):
plot_gage_subbasin(folder, self.HUC8, self.gageid, hspfmodel,
output = watershedplot)
示例5: plot_HUC8
# 需要导入模块: from shapefile import Reader [as 别名]
# 或者: from shapefile.Reader import shapes [as 别名]
def plot_HUC8(self,
flowfile,
cfile,
bfile,
VAAfile,
elevfile,
patchcolor = None,
resolution = 400,
colormap = 'gist_earth',
grid = False,
title = None,
verbose = True,
output = None,
show = False,
):
"""Makes a plot of the raw NHDPlus data."""
if verbose: print('generating plot of the watershed\n')
fig = pyplot.figure()
subplot = fig.add_subplot(111, aspect = 'equal')
subplot.tick_params(axis = 'both', which = 'major', labelsize = 10)
# add the title
if title is not None: subplot.set_title(title, fontsize = 14)
if patchcolor is None: facecolor = (1,0,0,0.)
else: facecolor = patchcolor
# open up and show the boundary
b = Reader(bfile, shapeType = 5)
boundary = b.shape(0)
points = numpy.array(boundary.points)
subplot.add_patch(self.make_patch(points, facecolor, width = 0.5))
# open up and show the catchments
c = Reader(cfile, shapeType = 5)
extent = self.get_boundaries(c.shapes(), space = 0.02)
xmin, ymin, xmax, ymax = extent
# figure out how far one foot is on the map
points_per_width = 72 * 8
ft_per_km = 3280.84
scale_factor = (points_per_width /
self.get_distance([xmin, ymin], [xmax, ymin]) /
ft_per_km)
# make patches of the catchment area
for i in range(len(c.records())):
catchment = c.shape(i)
points = numpy.array(catchment.points)
subplot.add_patch(self.make_patch(points, facecolor, width = 0.1))
# get the flowline attributes, make an "updown" dictionary to follow
# flow, and change the keys to comids
with open(VAAfile, 'rb') as f: flowlineVAAs = pickle.load(f)
updown = {}
for f in flowlineVAAs:
if flowlineVAAs[f].down in flowlineVAAs:
updown[flowlineVAAs[f].comid] = \
flowlineVAAs[flowlineVAAs[f].down].comid
flowlineVAAs = {flowlineVAAs[f].comid:flowlineVAAs[f]
for f in flowlineVAAs}
# open up and show the flowfiles
f = Reader(flowfile, shapeType = 3)
comid_index = f.fields.index(['COMID', 'N', 9, 0]) - 1
all_comids = [r[comid_index] for r in f.records()]
# get the flows and velocities from the dictionary
widths = []
comids = []
for comid in all_comids:
if comid in flowlineVAAs:
flow = flowlineVAAs[comid].flow
velocity = flowlineVAAs[comid].velocity
# estimate flow width (ft) assuming triangular 90 d channel
comids.append(comid)
widths.append(numpy.sqrt(4 * flow / velocity))
# convert widths in feet to points on the figure; exaggerated by 10
widths = [w * scale_factor * 20 for w in widths]
#.........这里部分代码省略.........
示例6: extract_bbox
# 需要导入模块: from shapefile import Reader [as 别名]
# 或者: from shapefile.Reader import shapes [as 别名]
def extract_bbox(self, bbox, output, verbose = True):
"""Extracts the NID dam locations for a watershed from the dam
shapefile and the 8-digit hydrologic unit code of interest.
"""
self.download_compressed()
xmin, ymin, xmax, ymax = bbox
# copy the projection files
if verbose: print('copying the projections from the NID source\n')
projection = self.source + '.prj'
shutil.copy(projection, output + '.prj')
# get the dams within the watershed
if verbose: print('reading the dam file\n')
sf = Reader(self.source, shapeType = 1)
# work around for issues with pyshp
damrecords = []
for i in range(len(sf.shapes())):
try: damrecords.append(sf.record(i))
except: damrecords.append([-100 for i in range(len(sf.fields))])
name_index = sf.fields.index(['DAM_NAME', 'C', 65, 0]) - 1
nid_index = sf.fields.index(['NIDID', 'C', 7, 0]) - 1
long_index = sf.fields.index(['LONGITUDE', 'N', 19, 11]) - 1
lat_index = sf.fields.index(['LATITUDE', 'N', 19, 11]) - 1
river_index = sf.fields.index(['RIVER', 'C', 65, 0]) - 1
owner_index = sf.fields.index(['OWN_NAME', 'C', 65, 0]) - 1
type_index = sf.fields.index(['DAM_TYPE', 'C', 10, 0]) - 1
purp_index = sf.fields.index(['PURPOSES', 'C', 254, 0]) - 1
year_index = sf.fields.index(['YR_COMPL', 'C', 10, 0]) - 1
high_index = sf.fields.index(['NID_HEIGHT', 'N', 19, 11]) - 1
mstor_index = sf.fields.index(['MAX_STOR', 'N', 19, 11]) - 1
nstor_index = sf.fields.index(['NORMAL_STO', 'N', 19, 11]) - 1
area_index = sf.fields.index(['SURF_AREA', 'N', 19, 11]) - 1
# iterate through the fields and determine which points are in the box
if verbose: print('extracting dams into new file\n')
dam_indices = []
i = 0
for record in damrecords:
lat = record[lat_index]
lon = record[long_index]
if self.inside_box([xmin, ymin], [xmax, ymax], [lon, lat]):
dam_indices.append(i)
i+=1
# write the data from the bbox to a new shapefile
w = Writer(shapeType = 1)
for field in sf.fields: w.field(*field)
for i in dam_indices:
point = sf.shape(i).points[0]
w.point(*point)
values = damrecords[i]
rs = []
for value in values:
if isinstance(value, bytes): value = value.decode('utf-8')
rs.append(value)
w.record(*rs)
w.save(output)
if verbose:
print('successfully extracted NID dam locations to new file\n')
示例7: cos
# 需要导入模块: from shapefile import Reader [as 别名]
# 或者: from shapefile.Reader import shapes [as 别名]
for c in ["maize", "wheat", "soy", "rice"]:
careas[c] = f.variables["area_" + c][:]
# find valid fpus
tarea = 100 * (111.2 / 2) ** 2 * cos(pi * lats / 180)
tarea = resize(tarea, (nlons, nlats)).T
validfpus = []
for i in range(nfpu):
hareafpu = harea[fpumap == fpu[i]].sum()
tareafpu = tarea[fpumap == fpu[i]].sum()
if hareafpu / tareafpu > percent / 100.0:
validfpus.append(fpu[i])
# load shape file
r = Reader(shapefile)
shapes = r.shapes()
records = r.records()
models = ["epic", "gepic", "lpj-guess", "lpjml", "pdssat", "pegasus"] # exclude image
gcms = ["gfdl-esm2m", "hadgem2-es", "ipsl-cm5a-lr", "miroc-esm-chem", "noresm1-m"]
crops = ["maize", "wheat", "soy", "rice"] if crop == "all" else [crop]
co2s = ["co2", "noco2"]
hadgemidx = gcms.index("hadgem2-es")
nm, ng, ncr, nco2 = len(models), len(gcms), len(crops), len(co2s)
# variables
sh = (nm, ng, ncr, 3, nfpu, nco2)
dy26arr = masked_array(zeros(sh), mask=ones(sh))
dy85arr = masked_array(zeros(sh), mask=ones(sh))
示例8: plot_landuse
# 需要导入模块: from shapefile import Reader [as 别名]
# 或者: from shapefile.Reader import shapes [as 别名]
#.........这里部分代码省略.........
im = subplot.imshow(image_array, extent = bbox,
origin = 'upper left',
interpolation = 'nearest',
cmap = cmap, norm = norm)
# adjust the plot bounding box
xmin, xmax = xmin-border * (xmax-xmin), xmax + border * (xmax-xmin)
ymin, ymax = ymin-border * (ymax-ymin), ymax + border * (ymax-ymin)
else:
# adjust the plot bounding box
xmin, xmax = xmin-border * (xmax-xmin), xmax + border * (xmax-xmin)
ymin, ymax = ymin-border * (ymax-ymin), ymax + border * (ymax-ymin)
# pixel width in latitude
pw = (xmax - xmin) / pixels
# calculate the image height in pixels
ny = int(numpy.ceil((ymax - ymin) / (xmax - xmin) * pixels))
# note the height of pixels = width of pixels
# and image width in pixels is "pixels"
xs = numpy.array([xmin + (i + 0.5) * pw for i in range(pixels)])
ys = numpy.array([ymin + (i + 0.5) * pw for i in range(ny)])
# set up an array of values for the image
zs = numpy.zeros((ny, pixels))
for i in range(len(ys)):
ps = [(x, ys[i]) for x in xs]
zs[i, :] = numpy.array(get_raster(landuse, ps, quiet = True))
zs = zs.astype(int)
tot = zs.size
for v in numpy.unique(zs):
group = self.groups[v]
i = self.order.index(group)
zs[numpy.where(zs == v)] = i
# plot the grid
im = subplot.imshow(zs,
interpolation = 'nearest',
origin = 'upper left',
extent = [xmin, xmax, ymin, ymax],
norm = norm,
cmap = cmap,
)
# add patch for the shape boundary
for shape in s.shapes():
points = numpy.array(shape.points)
subplot.add_patch(self.make_patch(points, (1,0,0,0), width=0.5))
# add the legend using a dummy box to make patches for the legend
dummybox = [[0,0], [0,1], [1,1], [1,0], [0,0]]
handles, labels = [], []
for group, color in zip(self.order[1:], color_table[1:]):
p = self.make_patch(dummybox, facecolor = color, width = 0)
handles.append(subplot.add_patch(p))
labels.append(group)
leg = subplot.legend(handles, labels, bbox_to_anchor = (1.0, 0.5),
loc = 'center left', title = 'Land Use Categories')
legtext = leg.get_texts()
pyplot.setp(legtext, fontsize = 10)
subplot.set_position([0.125, 0.1, 0.6, 0.8])
# add the labels and set the limits
subplot.set_xlabel('Longitude, Decimal Degrees', size = 13)
subplot.set_ylabel('Latitude, Decimal Degrees', size = 13)
subplot.set_xlim([xmin, xmax])
subplot.set_ylim([ymin, ymax])
subplot.xaxis.set_major_locator(ticker.MaxNLocator(8))
subplot.yaxis.set_major_locator(ticker.MaxNLocator(8))
subplot.xaxis.set_major_formatter(ticker.FormatStrFormatter('%.2f'))
subplot.yaxis.set_major_formatter(ticker.FormatStrFormatter('%.2f'))
# show it
if output is not None: pyplot.savefig(output)
if show: pyplot.show()
pyplot.clf()
pyplot.close()
示例9: print
# 需要导入模块: from shapefile import Reader [as 别名]
# 或者: from shapefile.Reader import shapes [as 别名]
# use the index to get the latitude and longitude of the station
x, y = reader.shape(j).points[0]
print('location of gage {}: {:.4f}, {:.4f}\n'.format(gageid, x, y))
# open the flowline shapefile to supply reach length (miles or kilometers
# depending on the unit system)
reader = Reader(flowfile)
# find shapes with a bounding box encompassing the gage to narrow the search
print('searching for the closest flowline to the gage\n')
bboxes = [s.bbox for s in reader.shapes()]
contains = [i for i, b in enumerate(bboxes)
if b[0] <= x and x <= b[2] and b[0] <= y and y <= b[3]]
# find the distances between all the overlapping shapes points and the gage
distances = [min([(x1 - x)**2 + (y1 - y)**2
for x1, y1 in reader.shape(i).points])
for i in contains]
# find the shape with the point closest to the gage
closest = contains[distances.index(min(distances))]
# read the record for the flowline
示例10: plot_climate
# 需要导入模块: from shapefile import Reader [as 别名]
# 或者: from shapefile.Reader import shapes [as 别名]
def plot_climate(HUC8, sfile, bfile, pfile = None, efile = None, tfile = None,
snowfile = None, centroids = True, radius = None,
patchcolor = None, solarfile = None, windfile = None,
output = None, show = False, verbose = True):
"""Makes a plot of all the hourly precipitation stations of a watershed
defined by "bfile" with subbasin defined by "sfile" from the source
precipitation shapefile "pfile"."""
if verbose:
print('generating plot of watershed %s NCDC stations\n' % HUC8)
fig = pyplot.figure()
subplot = fig.add_subplot(111, aspect = 'equal')
subplot.tick_params(axis = 'both', which = 'major', labelsize = 10)
# add the title
description = 'Climate Data Stations'
title = 'Cataloging Unit %s\n%s' % (HUC8, description)
subplot.set_title(title, fontsize = 14)
# open up and show the catchments
if patchcolor is None: facecolor = (1,0,0,0.)
else: facecolor = patchcolor
b = Reader(bfile, shapeType = 5)
points = np.array(b.shape(0).points)
subplot.add_patch(make_patch(points, facecolor = facecolor, width = 1.))
extent = get_boundaries(b.shapes(), space = 0.02)
xmin, ymin, xmax, ymax = extent
# add the subbasin file
s = Reader(sfile, shapeType = 5)
# make patches of the subbasins
for i in range(len(s.records())):
shape = s.shape(i)
points = np.array(shape.points)
subplot.add_patch(make_patch(points, facecolor, width = 0.15))
plots = [] # keep track of the scatterplots
names = [] # keep track of names for the legend
# add the subbasin centroids
if centroids:
cx_index = s.fields.index(['CenX', 'N', 12, 6]) - 1
cy_index = s.fields.index(['CenY', 'N', 12, 6]) - 1
centroids = [[r[cx_index], r[cy_index]] for r in s.records()]
xs, ys = zip(*centroids)
cplot = subplot.scatter(xs, ys, marker = '+', c = 'pink', s = 15)
plots.append(cplot)
names.append('Centroids')
# add a circle showing around subbasin "radius" showing the gages within
# the radius for a given subbasin
if radius is not None:
comid_index = s.fields.index(['ComID', 'N', 9, 0]) - 1
cx_index = s.fields.index(['CenX', 'N', 12, 6]) - 1
cy_index = s.fields.index(['CenY', 'N', 12, 6]) - 1
area_index = s.fields.index(['AreaSqKm', 'N', 10, 2]) - 1
comids = ['{}'.format(r[comid_index]) for r in s.records()]
cxs = [r[cx_index] for r in s.records()]
cys = [r[cy_index] for r in s.records()]
areas = [r[area_index] for r in s.records()]
try: i = comids.index(radius)
except: i = 0
c = [cxs[i], cys[i]]
radii = [math.sqrt(a / math.pi) for a in areas]
# scale kms to degrees
km = get_distance([xmin, ymin], [xmax, ymax])
deg = math.sqrt((xmin - xmax)**2 + (ymax - ymin)**2)
r = sum(radii) / len(radii) * deg / km * 5
circle = pyplot.Circle(c, radius = r, edgecolor = 'black',
facecolor = 'yellow', alpha = 0.5)
subplot.add_patch(circle)
subplot.scatter(c[0], c[1], marker = '+', c = 'black')
# add the precipitation gage points
if pfile is not None:
#.........这里部分代码省略.........
示例11: extract_aquifers
# 需要导入模块: from shapefile import Reader [as 别名]
# 或者: from shapefile.Reader import shapes [as 别名]
def extract_aquifers(directory, HUC8, aquifers, pad = 0.2, verbose = True):
"""Extracts aquifers from the source datafile to the destination using
the HUC8 boundaries for the query."""
start = time.time()
# open up the HUC8 boundary shapefile and use it to get the bounding box
shapefile = Reader(directory + '/%s/%scatchments' % (HUC8, HUC8))
xmin, ymin, xmax, ymax = get_boundaries(shapefile.shapes())
# convert to bounding corners for testing
p1 = [xmin - pad * (xmax - xmin), ymin - pad * (ymax - ymin)]
p2 = [xmax + pad * (xmax - xmin), ymax + pad * (ymax - ymin)]
shapefile = None
# start by copying the projection files
if verbose: print('\ncopying the projections\n')
shutil.copy(directory + '/%s/%scatchments.prj' % (HUC8, HUC8),
directory + '/%s/%saquifers.prj' % (HUC8, HUC8))
# open the flowline file
if verbose: print('reading the aquifer file\n')
shapefile = Reader(aquifers, shapeType = 5)
# work around for issues with pyshp
records = []
for i in range(len(shapefile.shapes())):
try: records.append(shapefile.record(i))
except: records.append('')
# use the bounding boxes to see if the shapes are within the watershed area
if verbose: print('searching for aquifers in the watershed\n')
bboxes = [shapefile.shape(i).bbox for i in range(len(records))]
corners = [[[b[0], b[1]], [b[0], b[3]], [b[2], b[1]], [b[2], b[3]]]
for b in bboxes]
indices = [i for i, c in zip(range(len(corners)), corners) if
any([inside_box(p1, p2, p) for p in c]) or
all([inside_box(c[0], c[3], p1), inside_box(c[0], c[3], p2)])]
# remove any non aquifers
indices = [i for i in indices if shapefile.record(i)[4] != 999]
# find a record for the non aquifer
i = 0
while shapefile.record(i)[4] != 999: i+=1
nonrecord = shapefile.record(i)
nonrecord[1] = nonrecord[1].decode('utf-8')
nonrecord[5] = 0
nonrecord[6] = 0
if len(indices) == 0:
if verbose: print('query returned no values, returning\n')
return
# write the data from the HUC8 to a new shapefile
w = Writer(shapeType = 5)
for field in shapefile.fields: w.field(*field)
for i in indices:
shape = shapefile.shape(i)
# check for multiple parts
if len(shape.parts) > 1:
parts = [shape.points[i:j]
for i, j in zip(shape.parts[:-1], shape.parts[1:])]
else: parts = [shape.points]
record = records[i]
# little work around for blank binary values
if isinstance(record[1], bytes):
record[1] = record[1].decode('utf-8')
w.poly(shapeType = 5, parts = parts)
w.record(*record)
# add a shape for the bounding box showing no aquifer locations
part = [p1, [p1[0], p2[1]], p2, [p2[0], p1[1]]]
#.........这里部分代码省略.........