以下是实现题目要求的Python代码: ```python def load_file(filename): with open(filename, 'r') as file: content = file.read() data = content.split(',') return data def get_subareas(data, city_name): subareas = [] for i in range(1, len(data)): if data[i] == city_name: j = i + 1 while j < len(data) and ',' not in data[j]: subareas.append(data[j]) j += 1 return subareas return None def get_parent_city(data, subarea_name): parent_cities = [] for i in range(1, len(data)): if ',' in data[i]: subareas = data[i].split(',') if subarea_name in subareas: parent_cities.append(data[i-1]) return parent_cities data = load_file("hebei.txt") print(data) user_input = input("请输入地级市名或市辖区、县或县级市名:") if user_input in data: subareas = get_subareas(data, user_input) if subareas: print(subareas) else: parent_cities = get_parent_city(data, user_input) if parent_cities: for city in parent_cities: print(city) else: print("找不到对应的市级或地级市名") else: print("找不到对应的地名") ``` 代码分为三个部分: 1. `load_file`函数用于读取文件内容并将其拆分为列表,每个元素为一个地名。 2. `get_subareas`函数根据用户输入的地级市名返回其下辖区、县和县级市的名称。 3. `get_parent_city`函数根据用户输入的市辖区、县或县级市名返回其上一级的地级市名,如果有多个地级市都有对应的市辖区名,则输出全部地级市名。 根据用户的输入分别调用相关函数并输出结果。 [2024-06-04 16:07:05 | AI写代码神器 | 1093点数解答]