import csv
import networkx as nx
# 创建图
G_undirected = nx.Graph() # 无向图,用于1号线和2号线
G_directed = nx.DiGraph() # 有向图,用于3号线
# 读取CSV文件并构建图
def load_data(filename):
with open(filename, 'r', encoding='utf-8') as file:
reader = csv.DictReader(file) # 使用DictReader方便通过列名访问数据
for row in reader:
line = row['line']
start_station = row['start_station']
end_station = row['end_station']
distance = int(row['distance'])
time = int(row['time'])
direction = row['direction']
# 根据线路类型添加边到相应的图
if line == "3号线":
G_directed.add_edge(start_station, end_station, distance=distance, time=time, direction=direction)
else:
G_undirected.add_edge(start_station, end_station, distance=distance, time=time)
# 打印图的信息以确认数据加载正确
def print_graph_info():
print("Undirected Graph (Lines 1 and 2):")
print("Nodes:", G_undirected.nodes())
print("Edges:", G_undirected.edges(data=True))
print("\nDirected Graph (Line 3):")
print("Nodes:", G_directed.nodes())
print("Edges:", G_directed.edges(data=True))
# 主函数
def main():
load_data('subway') # 确保CSV文件名和路径正确
print_graph_info()
if __name__ == "__main__":
main()
为什么我的csv文件提示说找不到啊,它就叫subway啊,放在桌面不知道为什么无法找到它