NetworkX 3.2.1调用read_shp报AttributeError的问题咨询
问题原因
NetworkX 3.0及以上版本已移除核心库中的read_shp和write_shp函数,这些GIS文件交互功能不再属于NetworkX核心模块,因此你在3.2.1版本中找不到该方法,并非安装遗漏。
解决思路
方法1:降级NetworkX到2.x版本
如果希望继续使用原有代码,可将NetworkX降级至2.x系列(如2.8.8),该版本仍保留read_shp功能:
# Conda环境下 conda install networkx=2.8.8 # 或pip安装 pip install networkx==2.8.8
方法2:使用第三方库nx_shp替代
nx_shp是专门用于NetworkX与SHP文件交互的第三方库,完全替代原有的read_shp/write_shp功能:
- 安装库:
pip install nx_shp
- 修改代码:
import nx_shp G = nx_shp.read_shp(r'path\to\test.shp')
方法3:手动基于pyshp构建图
如果不想依赖额外库,可使用pyshp读取SHP文件后,手动构建NetworkX图:
- 安装
pyshp:
pip install pyshp
- 示例代码(以线要素为例):
import shapefile import networkx as nx G = nx.Graph() # 读取SHP文件 sf = shapefile.Reader(r'path\to\test.shp') # 遍历每个要素,提取坐标并添加边 for shape in sf.shapes(): coords = shape.points # 将连续坐标点连接为边 for idx in range(len(coords)-1): G.add_edge(tuple(coords[idx]), tuple(coords[idx+1]))
此方式可自定义处理要素属性、拓扑关系,适合复杂场景。
内容的提问来源于stack exchange,提问作者Spiran
相关产品推荐
相关产品推荐

