HL7 消息解析与树形结构构建 - 解决 'TypeError: 'method' object is not subscriptable' 错误
HL7 消息解析与树形结构构建 - 解决 'TypeError: 'method' object is not subscriptable' 错误
本文介绍了如何使用 Python 库解析 HL7 消息并构建树形结构来表示消息的各个部分,并解决解析过程中出现的 'TypeError: 'method' object is not subscriptable' 错误。
代码示例:
import hl7
from anytree import Node, RenderTree
# 读取 HL7 文件
with open(r'C:\Users\lenovo\Desktop\数据结构与算法C++\20084125-张亭-数据结构算法实验1\HL7\Hl7process\msgs.hl7', 'r') as f:
hl7_msg = f.read()
# 解析 HL7 消息
msg = hl7.parse(hl7_msg)
# 使用树形结构来表示 HL7 消息的各个部分
def build_tree(msg, parent=None):
node = Node(msg[0], parent=parent)
for field in msg[1:]:
if '|' in field:
field_name, field_value = field.split('|', 1)
child_node = Node(field_name, parent=node)
if len(field_value) > 0:
for subfield in field_value.split('^'):
build_tree(hl7.parse(subfield), parent=child_node)
else:
build_tree(hl7.parse(field), parent=node)
return node
root_node = build_tree(msg.segments())
# 使用递归算法对树形结构进行遍历和处理
def print_node(node):
if node.is_leaf:
print(f'{node.name}: {node.parent.children[0].value}')
else:
print(node.name)
for child in node.children:
print_node(child)
# 打印 HL7 消息的各个部分的名称和值
for pre, fill, node in RenderTree(root_node):
print_node(node)
错误原因:
在原始代码中,msg.segment 是一个方法,而不是一个列表或元组,因此不能通过 msg.segment[0] 这样的方式来访问它的第一个元素。
解决方法:
- 使用
msg.segments()方法获取所有的消息段。 - 在
build_tree()函数中对这些段进行遍历来构建树形结构。 - 修改第 13 行,使用
msg[0]来获取第一个消息段的名称。
代码修改后的解释:
msg.segments()方法返回一个包含所有消息段的列表,因此可以使用索引[0]获取第一个消息段。build_tree()函数使用msg[1:]获取从第二个消息段开始的所有段,并对它们进行遍历和处理。- 第 13 行使用
msg[0]来获取第一个消息段的名称,并将其作为树节点的名称。
总结:
通过修改代码,解决了 'TypeError: 'method' object is not subscriptable' 错误,并成功构建了 HL7 消息的树形结构。
原文地址: https://www.cveoy.top/t/topic/noUd 著作权归作者所有。请勿转载和采集!