This Python script takes an HL7 message and rearranges the segments whose name
starts with IN into alphabetical order.
# This function takes a flatwire HL7 message as its argument
# and returns the same HL7 message. Any group of segments that
# starts with IN is sorted into alphabetical order.
# So if the HL7 message had a group of IN1 and IN2 segments
# like this:
# IN1|3|Blah
# IN2|3|Ditch
# IN1|2|Blah
# IN1|1|Smith
# IN2|2|Ditch
# IN2|1|Ditch
# Then the expected order of the segments would be:
# IN1|1|Smith
# IN1|2|Blah
# IN1|3|Blah
# IN2|1|Ditch
# IN2|2|Ditch
# IN2|3|Ditch
# There are some boundary conditions that this routine will not handle well.
# 1. If a message has several groups of IN* segments separated by other types of segments,
# only the first group in IN* segments will be sorted.
# 2. The segments are sorted in alphabetical order, which means that if field 1 of the INI
# segment goes into 2 characters, one gets some unexpected results. For example,
# IN1|4|blah
# IN1|30|blah
# IN1|5|delta
# gets sorted into
# IN1|30|blah
# IN1|4|blah
# IN1|5|delta
# So make sure that the message data you have does not generate sequences like the above.
defsort_ini(value):
# We start by breaking the message into a Python list object of segments
# See http://www.interfaceware.com/manual/python_lists.html
segment_list = value.split('\r')
# Now we're going to create three empty lists - the idea is to sort the segments
# into a list of segments before the IN* segments, the list of IN* segments and
# a list of IN* segments afterwards.
before_ini = []
ini_list = []
after_ini = []
reached_ini = 0 # i.e. false - we'll flip this flag when we reach the IN* segments
# We iterate through list of segments, put the ones
# before the IN* segments into the before_ini list,
# the IN* segments into ini_list
# and the ones afterwards in after_ini
# See http://www.interfaceware.com/manual/python_string_indexing.html
# to understand the syntax used here for python string manipulation
for segment in segment_list:
if segment[0:2] == "IN":
ini_list.append(segment)
reached_ini = 1
elif reached_ini:
after_ini.append(segment)
else:
before_ini.append(segment)
# Now we use the python sort method to sort the list of INI segments
# It does it alphabetically
ini_list.sort()
# Then concatenate the lists together again
complete_list = before_ini + ini_list + after_ini
# This final command joins the segment strings together again, putting the \r
# segment delimiters back in.
return"\r".join(complete_list)
# This is how to call our INI swap function
# value should contain a complete HL7 message
value = sort_ini(value)