首页 > 解决方案 > 如何使用 python HL7Apy 正确解析 HL7 消息?

问题描述

这是我的代码:

from hl7apy.parser import parse_message

hl7 = open("hl7.txt", "r").read()
msg = parse_message(hl7)
print(msg.children)

结果:

[<Segment MSH>]

它只显示第一段,看起来很简单,但我不知道我做错了什么。

我尝试过从文本文件中直接传递消息,甚至使用另一条 HL7 消息传递,但总是得到相同的结果。

这是消息:

MSH|^~\&|SendingAPP|TEST|||20080617143943||ORU^R01|1|P|2.3.1||||||UNICODE
PID|1||7393670^^^^MR||Joan^JIang||19900804000000|Female
PV1|1||nk^^001
OBR|1||20071207011|00001^Automated Count^99MRC||20080508140600|20080508150616|||John||||20080508150000||||||||||HM||||||||TEST

这是我在记事本++中的消息,其中显示了所有字符: 记事本++中的消息

标签: pythonhl7

解决方案


我认为您的问题是 HL7apy 的 MLLP 常量是Carriage return \r。如果您替换新行字符\n,组将解析得很好

from hl7apy.parser import parse_message
from hl7apy.core import Group, Segment

hl7 = """
MSH|^~\&|SendingAPP|TEST|||20080617143943||ORU^R01|1|P|2.3.1||||||UNICODE
PID|1||7393670^^^^MR||Joan^JIang||19900804000000|Female PV1|1||nk^^001
OBR|1||20071207011|00001^Automated
Count^99MRC||20080508140600|20080508150616|||John||||20080508150000||||||||||HM||||||||TEST
"""

msg = parse_message(hl7.replace('\n', '\r'), find_groups=True, validation_level=2)
print(msg.children)
print(msg.children[1].children)

for segment in msg.children:
    if isinstance(segment, Segment):
        for attribute in segment.children:
            print(attribute, attribute.value)
    if isinstance(segment, Group):
        for group in segment.children:
            for group_segment in group.children:
                for attribute in group_segment.children:
                    print(attribute, attribute.value)

推荐阅读