You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python将ICD-10 XML文件转换为RDF格式?

Solution: Generate Text Hierarchy and RDF from ICD-10 XML

1. Key Fixes & Improvements

Your original code was missing two critical pieces: generating the indented text output, and properly modeling parent-child relationships in RDF. Here's the corrected implementation that addresses both requirements:

2. Complete Code

import xml.etree.ElementTree as ET
from rdflib import Graph, Namespace, URIRef, Literal

# Initialize RDF graph and namespace
ICD_NS = Namespace("http://example.com/icd/")
graph = Graph()
graph.bind("icd", ICD_NS)  # Bind namespace to a prefix for cleaner RDF output

def process_element(element, parent_uri, depth=0):
    # Extract name and description (with safety checks)
    name_elem = element.find("name")
    desc_elem = element.find("description")
    name = name_elem.text.strip() if name_elem is not None and name_elem.text else "Unnamed"
    description = desc_elem.text.strip() if desc_elem is not None and desc_elem.text else "No description"
    
    # Generate indented text output
    indent = " " * depth * 2
    print(f"{indent}{description} ({name})")
    
    # Create URI for current element (sanitize invalid characters)
    sanitized_name = name.replace('/', '_').replace('#', '_')
    element_uri = URIRef(f"{ICD_NS}{sanitized_name}")
    
    # Add core RDF triples
    graph.add((element_uri, ICD_NS.name, Literal(name)))
    graph.add((element_uri, ICD_NS.description, Literal(description)))
    graph.add((element_uri, ICD_NS.type, Literal(element.attrib.get('type', 'unknown'))))
    
    # Link to parent if exists
    if parent_uri is not None:
        graph.add((element_uri, ICD_NS.hasParent, parent_uri))
    
    # Recursively process child elements
    for child in element.findall("item"):
        process_element(child, element_uri, depth + 1)

# Load and parse XML file
tree = ET.parse('icd10_v19.xml')
root = tree.getroot()

# Start processing from top-level items (chapters)
for top_item in root.findall("item"):
    process_element(top_item, None, depth=0)

# Save RDF to file
graph.serialize(destination="icd10_graph.rdf", format='xml')

3. Explanation

Text Hierarchy Generation

  • The depth parameter tracks the current level in the ICD hierarchy (0 for chapters, 1 for blocks, etc.)
  • Indentation is calculated as 2 * depth spaces to match your desired output format
  • Each line prints the description followed by the code in parentheses

RDF Graph Improvements

  • Valid URIs: Element URIs are sanitized to remove characters that break URI syntax (like slashes or hashes)
  • Parent-Child Relationships: The icd:hasParent predicate explicitly links each element to its parent, preserving the hierarchy in RDF
  • Namespace Binding: The icd prefix is bound to your namespace, making the RDF output human-readable
  • Safety Checks: Added guards for missing name/description attributes to avoid runtime errors

4. Example Output

Text Output

Certain infectious and parasitic diseases (I)
  Intestinal infectious diseases (A00-A09)
    Cholera (A00)
      Cholera due to Vibrio cholerae 01, biovar cholerae (A00.0)
      Cholera due to Vibrio cholerae 01, biovar eltor (A00.1)
      Cholera, unspecified (A00.9)
    Typhoid and paratyphoid fevers (A01)
      Typhoid fever (A01.0)
      ...

RDF Structure

The generated RDF will include triples like:

<icd:I>
  <icd:name>I</icd:name>
  <icd:description>Certain infectious and parasitic diseases</icd:description>
  <icd:type>chapter</icd:type>
</icd:I>
<icd:A00-A09>
  <icd:name>A00-A09</icd:name>
  <icd:description>Intestinal infectious diseases</icd:description>
  <icd:type>block</icd:type>
  <icd:hasParent rdf:resource="http://example.com/icd/I"/>
</icd:A00-A09>

内容的提问来源于stack exchange,提问作者rshar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 21:24:58