NetworkX:从shapefile

时间:2017-06-27 10:34:59

标签: python filenames networkx shapefile

假设您有以下目录,其中包含多个shapefile:

MyFolder
|
|---S1.shp
|---S2.shp
|---S3.shp
|---
|---
|---S50.shp

并且您希望为其中每一个创建一个图表,并将其称为相同(例如,与S1.shp相关联的图表称为S1)。

我试图在for循环中执行此操作:

import networkx as nx
import os

myfolder=r'C:\Users\MyName\MyFolder'
os.chdir(myfolder) 
for root, dirs, filenames in os.walk(myfolder):
    for f in filenames:
        if f.endswith('.shp') and f[0]=='S': #Consider only the files with an "S" in their name
            G=nx.read_shp(f)
            pos={k: v for k,v in enumerate(G.nodes())}
            pos_x = {k:(round(a,4),round(b,4)) for k,(a,b) in pos.items()}
            graph_name=f.split('.', 1)[0]
            GG=nx.Graph(name=graph_name)  
            GG.add_nodes_from(pos_x.keys())

现在GG=nx.Graph(name=graph_name)行没有按照我的意愿行事,因为图表仍称为GG,而不是S1等。正确的图形名称存储在GG.name中,但我无法通过调用其GG.name来检索图形。

有没有办法可以为图表指定 文件名的名称,而不包含扩展名?

1 个答案:

答案 0 :(得分:1)

您可以将GG设为将文件名映射到图表的字典:

import networkx as nx
import os

myfolder = r'C:\Users\MyName\MyFolder'
os.chdir(myfolder)
GG = dict()
for root, dirs, filenames in os.walk(myfolder):
    for f in filenames:
        if f.endswith('.shp') and f.startswith('S'):
            G = nx.read_shp(f)
            pos_x = {k: (round(a, 4), round(b, 4))
                     for k, (a, b) in enumerate(G.nodes())}
            graph_name, graph_ext = os.path.splitext(f)
            GG[graph_name] = nx.Graph(name=graph_name)
            GG[graph_name].add_nodes_from(pos_x.keys())

然后S1.shp可以访问与GG['S1']相关联的图表。