You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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功能:

  1. 安装库:
pip install nx_shp
  1. 修改代码:
import nx_shp
G = nx_shp.read_shp(r'path\to\test.shp')

方法3:手动基于pyshp构建图

如果不想依赖额外库,可使用pyshp读取SHP文件后,手动构建NetworkX图:

  1. 安装pyshp:
pip install pyshp
  1. 示例代码(以线要素为例):
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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 19:11:02