使用BeautifulSoup拆分含子标签的标签 实现HTML词典转XML
处理方案
你遇到的问题核心是<definition>标签下混合了文本节点和子标签,无法直接对整体内容调用split,正确的处理方式是遍历标签的所有子节点(包括文本节点和子标签)按分隔符分组,不需要完全重建所有标签,可直接复用已有的<example>节点。
你可以在完成example标签拆分后,运行以下代码处理definition标签:
from bs4 import NavigableString import re # 遍历所有definition标签 definition_tags = soup.find_all("definition") for def_tag in definition_tags: sense_groups = [] current_def_text = "" current_example_list = [] # 遍历definition下的所有子节点,包括文本和子标签 for node in def_tag.contents: # 处理文本节点,按分隔符拆分生成新分组 if isinstance(node, NavigableString): text_content = node.strip() if not text_content: continue # 按;加任意空白字符拆分文本 split_parts = re.split(r";\s*", text_content) # 第一部分追加到当前释义文本 if split_parts[0]: current_def_text += split_parts[0] # 剩下的每个部分对应新的释义分组 for part in split_parts[1:]: # 存储当前已完成的分组 sense_groups.append({ "definition": current_def_text.strip(), "examples": current_example_list.copy() }) # 重置当前分组的内容 current_def_text = part.strip() current_example_list.clear() # 处理example子标签,直接归入当前分组 elif node.name == "example": # 把example从原节点中提取出来,后续直接复用 current_example_list.append(node.extract()) # 存储最后一个未入库的分组 if current_def_text: sense_groups.append({ "definition": current_def_text.strip(), "examples": current_example_list }) # 生成sense标签替换原definition标签 parent_node = def_tag.parent for group in sense_groups: sense_tag = soup.new_tag("sense") # 生成新的definition标签存储释义 new_def_tag = soup.new_tag("definition") new_def_tag.string = group["definition"] sense_tag.append(new_def_tag) # 插入对应示例 for eg_tag in group["examples"]: sense_tag.append(eg_tag) # 把sense插入到原definition标签之前 def_tag.insert_before(sense_tag) # 删除原有的definition标签 def_tag.decompose()
运行以上代码后,即可得到你预期的XML结构。
内容的提问来源于stack exchange,提问作者Moilleadóir
相关产品推荐
相关产品推荐

