如何在Python中匹配XML枚举代码与TXT文件的字符串字面量?
Python实现XML枚举值与TXT字符串匹配的方案
步骤1:读取TXT文件,构建代码与字面量的映射字典
先从TXT文件中提取车辆代码和对应的字面量,生成字典用于快速查询:
def build_vehicle_literal_map(txt_path): vehicle_map = {} with open(txt_path, 'r', encoding='utf-8') as f: lines = f.readlines() # 跳过标题行、分隔线和空行 for line in lines[3:]: line = line.strip() if not line: continue # 按空格分割(仅分割一次,避免字面量含空格导致错误) code, literal = line.split(maxsplit=1) vehicle_map[code.strip()] = literal.strip() return vehicle_map
步骤2:解析XML文件,提取所有枚举值
用Python内置的xml.etree.ElementTree解析XML,提取所有枚举值:
import xml.etree.ElementTree as ET def extract_xml_enumerations(xml_path): enumerations = [] # 定义XML命名空间 ns = {'xs': 'http://www.w3.org/2001/XMLSchema'} tree = ET.parse(xml_path) root = tree.getroot() # 查找所有枚举元素并提取value属性 enum_elements = root.findall('.//xs:enumeration', ns) for elem in enum_elements: enum_value = elem.get('value') if enum_value: enumerations.append(enum_value) return enumerations
步骤3:匹配枚举值与字面量并输出
将XML提取的枚举值与TXT字典匹配,输出结果:
def main(xml_path, txt_path): vehicle_map = build_vehicle_literal_map(txt_path) enum_values = extract_xml_enumerations(xml_path) print("枚举值与对应字面量匹配结果:") for code in enum_values: literal = vehicle_map.get(code, "未找到对应字面量") print(f"{code} -> {literal}") # 替换为你的实际文件路径 if __name__ == "__main__": main("enumerations.xml", "vehicle_literals.txt")
关键说明
- TXT处理跳过前3行无效内容,确保只读取有效数据
- 分割行时用
maxsplit=1,避免字面量中的空格被误拆分 - XML解析处理了命名空间,保证能正确定位枚举元素
- 若枚举值在TXT中无匹配,会显示默认提示文本
内容的提问来源于stack exchange,提问作者Kyle Hatfield
相关产品推荐
相关产品推荐

