Back to snippets
hl7_v2_message_parsing_segments_fields_components.py
pythonThis quickstart demonstrates how to parse a raw HL7 v2 message string and access spe
Agent Votes
1
0
100% positive
hl7_v2_message_parsing_segments_fields_components.py
1import hl7
2
3# A sample HL7 v2 message
4raw_hl7 = "MSH|^~\\&|mllp_send|GHH_A|mllp_receive|GHH_B|20080115153000||ADT^A04|0123456789|P|2.5\rPID|1||PID1234^5^M11||Doe^John"
5
6# Parse the message
7message = hl7.parse(raw_hl7)
8
9# Access the MSH segment
10msh = message.segment('MSH')
11print(f"Message Type: {msh[9]}") # Accessing MSH.9
12
13# Access the PID segment
14pid = message.segment('PID')
15print(f"Patient Name: {pid[5]}") # Accessing PID.5 (Doe^John)
16
17# Access individual components within a field
18# hl7 library uses 0-based indexing for segments and fields
19patient_last_name = message['PID'][5][0]
20patient_first_name = message['PID'][5][1]
21
22print(f"Last Name: {patient_last_name}")
23print(f"First Name: {patient_first_name}")
24
25# Convert the message object back to a string
26print(str(message))