当前位置: 首页>>代码示例>>Python>>正文


Python shapefile.Reader方法代码示例

本文整理汇总了Python中shapefile.Reader方法的典型用法代码示例。如果您正苦于以下问题:Python shapefile.Reader方法的具体用法?Python shapefile.Reader怎么用?Python shapefile.Reader使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在shapefile的用法示例。


在下文中一共展示了shapefile.Reader方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: draw_polygons

# 需要导入模块: import shapefile [as 别名]
# 或者: from shapefile import Reader [as 别名]
def draw_polygons(self):
        sf = shapefile.Reader(self.shapefile)       
        polygons = sf.shapes() 
        for polygon in polygons:
            polygon = shapely.geometry.shape(polygon)
            if polygon.geom_type == 'Polygon':
                polygon = [polygon]
            for land in polygon:
                qt_polygon = QPolygonF() 
                for lon, lat in land.exterior.coords:
                    px, py = self.to_canvas_coordinates(lon, lat)
                    if px > 1e+10:
                        continue
                    qt_polygon.append(QPointF(px, py))
                polygon_item = QGraphicsPolygonItem(qt_polygon)
                polygon_item.setBrush(QBrush(QColor(52, 165, 111)))
                polygon_item.setZValue(1)
                yield polygon_item 
开发者ID:afourmy,项目名称:pyGISS,代码行数:20,代码来源:pyGISS.py

示例2: draw_polygons

# 需要导入模块: import shapefile [as 别名]
# 或者: from shapefile import Reader [as 别名]
def draw_polygons(self):
        sf = shapefile.Reader(self.shapefile)       
        polygons = sf.shapes() 
        for polygon in polygons:
            # convert shapefile geometries into shapely geometries
            # to extract the polygons of a multipolygon
            polygon = shapely.geometry.shape(polygon)
            # if it is a polygon, we use a list to make it iterable
            if polygon.geom_type == 'Polygon':
                polygon = [polygon]
            for land in polygon:
                qt_polygon = QPolygonF() 
                for lon, lat in land.exterior.coords:
                    print(lon, lat)
                    px, py = self.to_canvas_coordinates(lon, lat)
                    if px > 1e+10:
                        continue
                    qt_polygon.append(QPointF(px, py))
                polygon_item = QGraphicsPolygonItem(qt_polygon)
                polygon_item.setBrush(self.land_brush)
                polygon_item.setPen(self.land_pen)
                polygon_item.setZValue(1)
                yield polygon_item 
开发者ID:afourmy,项目名称:pyGISS,代码行数:25,代码来源:extended_pyGISS.py

示例3: draw_map

# 需要导入模块: import shapefile [as 别名]
# 或者: from shapefile import Reader [as 别名]
def draw_map(self):
        self.delete('land', 'water')
        self.draw_water()
        sf = shapefile.Reader(self.filepath)
        polygons = sf.shapes()
        for polygon in polygons:
            # convert shapefile geometries into shapely geometries
            # to extract the polygons of a multipolygon
            polygon = shapely.geometry.shape(polygon)
            if polygon.geom_type == 'Polygon':
                polygon = [polygon]
            for land in polygon:
                self.create_polygon(
                    sum((self.to_canvas_coordinates(*c) for c in land.exterior.coords), ()),
                    fill='green3',
                    outline='black',
                    tags=('land',)
                ) 
开发者ID:afourmy,项目名称:pyGISS,代码行数:20,代码来源:pyGISS.py

示例4: draw_map

# 需要导入模块: import shapefile [as 别名]
# 或者: from shapefile import Reader [as 别名]
def draw_map(self):
        if not self.filepath:
            return
        self.delete('land', 'water')
        self.ratio, self.offset = 1, (0, 0)
        self.draw_water()
        sf = shapefile.Reader(self.filepath)       
        polygons = sf.shapes() 
        for polygon in polygons:
            polygon = shapely.geometry.shape(polygon)
            if polygon.geom_type == 'Polygon':
                polygon = [polygon]
            for land in polygon:
                self.create_polygon(
                    sum((self.to_canvas_coordinates(*c) for c in land.exterior.coords), ()),    
                    fill = 'green3', 
                    outline = 'black', 
                    tags = ('land',)
                )
        self.redraw_nodes() 
开发者ID:afourmy,项目名称:pyGISS,代码行数:22,代码来源:extended_pyGISS.py

示例5: calc_bounding_box_geom

# 需要导入模块: import shapefile [as 别名]
# 或者: from shapefile import Reader [as 别名]
def calc_bounding_box_geom(self, geometry_shapefile):
        import shapefile
        sf = shapefile.Reader(geometry_shapefile)
        shapes = sf.shapes()
        len_shapes = len(shapes)
        bwidth = []
        blength = []
        for shape in range(len_shapes):
            bbox = shapes[shape].bbox
            coords_bbox = [coord for coord in bbox]
            delta1 = abs(coords_bbox[0] - coords_bbox[2])
            delta2 = abs(coords_bbox[1] - coords_bbox[3])
            if delta1 >= delta2:
                bwidth.append(delta2)
                blength.append(delta1)
            else:
                bwidth.append(delta1)
                blength.append(delta2)

        return blength, bwidth 
开发者ID:architecture-building-systems,项目名称:CityEnergyAnalyst,代码行数:22,代码来源:building_properties.py

示例6: main

# 需要导入模块: import shapefile [as 别名]
# 或者: from shapefile import Reader [as 别名]
def main(shapefilename, outfilename):
    # define index from record for zone name
    s = sf.Reader(shapefilename)
    shape_records = s.shapeRecords()

    conversion_option = get_conversion_option(shape_records)

    if get_var_names() == 0:
        x_var_name = 'x'
        y_var_name = 'y'
    else:
        x_var_name = 'lon'
        y_var_name = 'lat'
    dataset = tp.active_frame().create_dataset("Shapefile", [x_var_name, y_var_name])

    if conversion_option == 1:  # Single Zone
        start = time.time()
        convert_to_single_zone(s, os.path.basename(shapefilename), dataset)
    else:  # One Zone per Shape
        name_index = get_name_index(s)
        start = time.time()
        convert_to_one_zone_per_shape(s, name_index, dataset)
    tp.data.save_tecplot_plt(outfilename)
    print("Elapsed time: ", time.time() - start) 
开发者ID:Tecplot,项目名称:handyscripts,代码行数:26,代码来源:shapefile_to_plt.py

示例7: highlight_area

# 需要导入模块: import shapefile [as 别名]
# 或者: from shapefile import Reader [as 别名]
def highlight_area(
    area: Union[Array_T, str], linecolor: str = "red", **kwargs
) -> List[Line2D]:
    r"""Return list of Line2D object for given area name"""
    fpath = os.path.join(MODULE_DIR, "data", "shapefile", "City")
    shp = shapefile.Reader(fpath, encoding="gbk")
    rec = shp.shapeRecords()
    lines = list()
    if isinstance(area, str):
        area = [area]
    for i in area:
        if not isinstance(i, str):
            raise RadarPlotError("Area name should be str")
        name = np.array([i.record[2] for i in rec])
        target = np.array(rec)[(name == i).nonzero()[0]]
        for j in target:
            pts = j.shape.points
            x = [i[0] for i in pts]
            y = [i[1] for i in pts]
            lines.append(Line2D(x, y, color=linecolor))
    return lines 
开发者ID:CyanideCN,项目名称:PyCINRAD,代码行数:23,代码来源:utils.py

示例8: draw_polygons

# 需要导入模块: import shapefile [as 别名]
# 或者: from shapefile import Reader [as 别名]
def draw_polygons(self):
        sf = shapefile.Reader(self.shapefile)       
        polygons = sf.shapes() 
        for polygon in polygons:
            # convert shapefile geometries into shapely geometries
            # to extract the polygons of a multipolygon
            polygon = shapely.geometry.shape(polygon)
            # if it is a polygon, we use a list to make it iterable
            if polygon.geom_type == 'Polygon':
                polygon = [polygon]
            for land in polygon:
                qt_polygon = QtGui.QPolygonF() 
                longitudes, latitudes = land.exterior.coords.xy
                for lon, lat in zip(longitudes, latitudes):
                    px, py = self.to_canvas_coordinates(lon, lat)
                    if px > 1e+10:
                        continue
                    qt_polygon.append(QtCore.QPointF(px, py))
                polygon_item = QtWidgets.QGraphicsPolygonItem(qt_polygon)
                polygon_item.setBrush(self.land_brush)
                polygon_item.setPen(self.land_pen)
                polygon_item.setZValue(1)
                yield polygon_item 
开发者ID:afourmy,项目名称:pyNMS,代码行数:25,代码来源:geographical_view.py

示例9: _area

# 需要导入模块: import shapefile [as 别名]
# 或者: from shapefile import Reader [as 别名]
def _area(self, report_id, year):

        url = self.BASE + '/cgi-bin/report.py'

        analysis = {"analysis_type": "area_profile_report",
                    "job_type": 'jt00',
                    "ap_segment": "s000",
                    "origin": 'home',
                    "color": ["#0000AA"]}

        params = {'report_id': report_id,
                  'settings': json.dumps(analysis),
                  'mode': 'export_geography',
                  'format': 'shp'}

        response = self.get(url, params=params)

        z = zipfile.ZipFile(io.BytesIO(response.content))

        with z.open('points_{year}.dbf'.format(year=year)) as dbf:
            reader = shapefile.Reader(dbf=io.BytesIO(dbf.read()))
            fields = [field[0] for field in reader.fields[1:]]
            for row in reader.records():
                yield dict(zip(fields, row)) 
开发者ID:datamade,项目名称:census_area,代码行数:26,代码来源:lodes.py

示例10: Determine

# 需要导入模块: import shapefile [as 别名]
# 或者: from shapefile import Reader [as 别名]
def Determine(Basin, Home_folder):
      			
    Shape_file_name_shp = os.path.join(Home_folder,'Basins', Basin + '.shp')
    if not os.path.exists(Shape_file_name_shp):
        print '%s is missing' %Shape_file_name_shp				
    Shape_file_name_dbf = os.path.join(Home_folder,'Basins', Basin + '.dbf')
    if not os.path.exists(Shape_file_name_dbf):
        print '%s is missing' %Shape_file_name_dbf					

    Basin_shp = shapefile.Reader(Shape_file_name_shp, Shape_file_name_dbf)
    Shape = Basin_shp.shapes()
    bbox = Shape[0].bbox
    Boundaries = dict()
    #Boundaries['Lonmin'] = np.floor(bbox[0]) - 0.1
    #Boundaries['Lonmax'] = np.ceil(bbox[2]) + 0.1
    #Boundaries['Latmin'] = np.floor(bbox[1]) - 0.1
    #Boundaries['Latmax'] = np.ceil(bbox[3]) + 0.1
    Boundaries['Lonmin'] = round(np.floor((bbox[0] * 10.) - 1.))/10.
    Boundaries['Lonmax'] = round(np.ceil((bbox[2] * 10.) + 1.))/10.
    Boundaries['Latmin'] = round(np.floor((bbox[1] * 10.) - 1.))/10.
    Boundaries['Latmax'] = round((np.ceil(bbox[3] * 10.) + 1.))/10.				
    return(Boundaries, Shape_file_name_shp) 
开发者ID:wateraccounting,项目名称:wa,代码行数:24,代码来源:Boundaries.py

示例11: __init__

# 需要导入模块: import shapefile [as 别名]
# 或者: from shapefile import Reader [as 别名]
def __init__(self, fname, f_tooltip=None, color=None, linewidth=3, shape_type='full', encoding='utf-8', encodingErrors='strict'):
        """
        Loads and draws shapefiles

        :param fname: full path to the shapefile
        :param f_tooltip: function to generate a tooltip on mouseover
        :param color: color
        :param linewidth: line width
        :param shape_type: either full or bbox
        """
        if color is None:
            color = [255, 0, 0]
        self.color = color
        self.linewidth = linewidth
        self.f_tooltip = f_tooltip
        self.shape_type = shape_type

        try:
            import shapefile
        except:
            raise Exception('ShapefileLayer requires pyshp')

        self.reader = shapefile.Reader(fname, encoding=encoding, encodingErrors=encodingErrors)
        self.worker = None
        self.queue = Queue.Queue() 
开发者ID:andrea-cuttone,项目名称:geoplotlib,代码行数:27,代码来源:layers.py

示例12: read_shapefile

# 需要导入模块: import shapefile [as 别名]
# 或者: from shapefile import Reader [as 别名]
def read_shapefile(shp_path):
    """
        Read a shapefile into a Pandas dataframe with a 'coords' column holding
        the geometry information. This uses the pyshp package
        """
    import shapefile

    # read file, parse out the records and shapes
    sf = shapefile.Reader(shp_path)
    fields = [x[0] for x in sf.fields][1:]
    records = sf.records()
    shps = [s.points for s in sf.shapes()]

    # write into a dataframe
    df = pd.DataFrame(columns=fields, data=records)
    df = df.assign(coords=shps)

    return df 
开发者ID:aerispaha,项目名称:swmmio,代码行数:20,代码来源:spatial.py

示例13: DrawShapeFile

# 需要导入模块: import shapefile [as 别名]
# 或者: from shapefile import Reader [as 别名]
def DrawShapeFile(area):
        """
        在画布上绘制shp文件
        :param area: 包含shp文件名及线宽和线颜色的一个字典
        :return: 
        """
        try:
            shpfile = area.file
            border_shape = shapefile.Reader(shpfile)
            border = border_shape.shapes()
            for b in border:
                border_points = b.points
                path_data = []
                count = 0
                for cell in border_points:
                    if count == 0:
                        trans = (Path.MOVETO, (cell[0], cell[1]))
                        path_data += [trans]
                        cell_end = cell
                    else:
                        trans = (Path.CURVE4, (cell[0], cell[1]))
                        path_data += [trans]
                trans = (Path.CLOSEPOLY, (cell_end[0], cell_end[1]))
                path_data += [trans]

                codes, verts = list(zip(*path_data))
                path = Path(verts, codes)
                x, y = list(zip(*path.vertices))
                plt.plot(x, y, 'k-', linewidth=area.linewidth, color=area.linecolor)
        except Exception as err:
            print(u'【{0}】{1}-{2}'.format(area['file'], err, datetime.now())) 
开发者ID:flashlxy,项目名称:PyMICAPS,代码行数:33,代码来源:Map.py

示例14: getPathFromShp

# 需要导入模块: import shapefile [as 别名]
# 或者: from shapefile import Reader [as 别名]
def getPathFromShp(shpfile, region):
    try:
        sf = shapefile.Reader(shpfile)
        vertices = []  # 这块是已经修改的地方
        codes = []  # 这块是已经修改的地方
        paths = []
        for shape_rec in sf.shapeRecords():
            # if shape_rec.record[3] == region:  # 这里需要找到和region匹配的唯一标识符,record[]中必有一项是对应的。
            if region == [100000] or shape_rec.record[4] in region:  # 这块是已经修改的地方
                pts = shape_rec.shape.points
                prt = list(shape_rec.shape.parts) + [len(pts)]
                for i in range(len(prt) - 1):
                    for j in range(prt[i], prt[i + 1]):
                        vertices.append((pts[j][0], pts[j][1]))
                    codes += [Path.MOVETO]
                    codes += [Path.LINETO] * (prt[i + 1] - prt[i] - 2)
                    codes += [Path.CLOSEPOLY]
                path = Path(vertices, codes)
                paths.append(path)
        if paths:
            path = Path.make_compound_path(*paths)
        else:
            path = None
        return path
    except Exception as err:
        print(err)
        return None 
开发者ID:flashlxy,项目名称:PyMICAPS,代码行数:29,代码来源:maskout.py

示例15: load_shapes

# 需要导入模块: import shapefile [as 别名]
# 或者: from shapefile import Reader [as 别名]
def load_shapes(path):
    skip = set(['02', '15', '60', '66', '69', '78', '72'])
    result = []
    sf = shapefile.Reader(path)
    for item in sf.shapeRecords():
        if item.record[0] in skip:
            continue
        result.extend(shape_to_polygons(item.shape))
    return result 
开发者ID:fogleman,项目名称:xy,代码行数:11,代码来源:usa.py


注:本文中的shapefile.Reader方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。