从公交时刻表文本文件构建换乘时间字典的技术实现问询
从公交时刻表文本文件构建换乘时间字典的技术实现问询
嗨,我来帮你搞定这个从公交时刻表生成换乘时间字典的需求!咱们先把需求再捋一遍:你有一个按线路划分的文本格式时刻表,要生成一个嵌套字典——外层键是站点名称,内层字典的键是其他站点,值是两个站点之间的分钟数,而且每一对站点的时间只需要存储一次,对吧?
先明确输入格式的核心特点
你的时刻表是按线路分组的:
1:
Maple Street 10:00
Oak Avenue 10:01
Elm Square 10:03
Cedar Lane 10:03
2:
Pine Boulevard 10:00
...
每条线路下的站点是按公交停靠顺序排列的,相邻站点的时间差就是它们之间的换乘时间,我们需要把这些时间差整理成要求的字典结构,同时避免重复存储同一对站点的时间。
具体实现思路(以Python为例)
我给你写一个可直接用的实现方案,分三步走:
1. 读取并解析文件
先把文件内容逐行读取,跳过空行,识别线路的起始标记(比如1:这样的行),然后收集每条线路下的站点和对应时间。
2. 时间格式转换
把HH:MM格式的时间转换成从0点开始的总分钟数,这样计算时间差会非常方便(比如10:00就是600分钟,10:03就是603分钟,差值直接用减法就能得到)。
3. 构建目标字典
遍历每条线路的站点序列,计算相邻站点的时间差,然后按照要求存入字典——这里我做了两种处理方式,你可以按需选:
- 方式一:按线路停靠顺序存储单向时间(比如线路里是Oak到Elm,就存
Oak Avenue: {Elm Square: 2}) - 方式二:按站点名称的字典序存储,确保每对站点只存一次(比如不管线路顺序是Oak到Elm还是Elm到Oak,都存成
Elm Square: {Oak Avenue: 2},因为Elm的字典序比Oak靠前)
代码实现
def build_bus_time_dict(file_path): time_dict = {} current_route_stops = [] def process_single_route(stops, target_dict, store_by_order=True): """处理单条线路的站点,生成时间差条目""" for i in range(len(stops) - 1): stop_a, time_a = stops[i] stop_b, time_b = stops[i+1] time_diff = abs(time_b - time_a) if store_by_order: # 按线路停靠顺序存储,不重复存同一方向 if stop_a not in target_dict: target_dict[stop_a] = {} if stop_b not in target_dict[stop_a]: target_dict[stop_a][stop_b] = time_diff else: # 按字典序存储,确保每对站点只存一次 key_first, key_second = (stop_a, stop_b) if stop_a < stop_b else (stop_b, stop_a) if key_first not in target_dict: target_dict[key_first] = {} if key_second not in target_dict[key_first]: target_dict[key_first][key_second] = time_diff # 读取并解析文件 with open(file_path, 'r', encoding='utf-8') as f: for line in f: stripped_line = line.strip() if not stripped_line: continue # 识别线路起始行(如"1:") if stripped_line.endswith(':'): # 先处理上一条线路的站点 if current_route_stops: process_single_route(current_route_stops, time_dict, store_by_order=True) current_route_stops = [] continue # 分割站点名和时间(站点名可能带空格,所以只分割一次) stop_name, time_str = stripped_line.split(maxsplit=1) hours, minutes = map(int, time_str.split(':')) total_minutes = hours * 60 + minutes current_route_stops.append((stop_name, total_minutes)) # 处理最后一条线路 if current_route_stops: process_single_route(current_route_stops, time_dict, store_by_order=True) return time_dict # 示例调用(替换成你的文件路径) # result = build_bus_time_dict("bus_schedule.txt") # import pprint # pprint.pprint(result)
代码关键点说明
- 用
split(maxsplit=1)分割站点名和时间:因为站点名可能包含空格(比如Maple Street),这个方法能确保前面的所有内容都被识别为站点名,最后一部分是时间。 process_single_route函数里的store_by_order参数:如果设为False,就会按字典序存储,彻底避免同一对站点的重复条目,完全符合你“时间只给出一次”的要求。- 用
abs()计算时间差:确保不管线路是正向还是反向(虽然你的输入是按停靠顺序,但保险起见),得到的都是正数分钟数。
测试一下你给的示例输入,运行后会生成包含"Oak Avenue": {"Elm Square": 2}这样的条目,完全符合你的预期。
备注:内容来源于stack exchange,提问作者mrLimpio
相关产品推荐
相关产品推荐

