#Intended as an auxiliary program for citations.tex to alphabetize an output file based on the first group. #Inputs file sort.tex, to sort as read, takes all data, and then reopens as write f = open('sort.tex','r') dat = f.readline().split('\\par ') f.close() f = open('sort.tex','w') def firstgroup(line): #handles nested brackets to return (first group data, other data) tuple. nesting = 0 for charind in range(len(line)): char = line[charind] if char == '{': nesting += 1 if char == '}': nesting -= 1 if nesting == 0: breakchar = charind+1 break return (line[1:breakchar], line[breakchar:]) for lineind in range(len(dat)): line = dat[lineind] dat[lineind] = firstgroup(line) dat.sort(key=lambda text : [ord(char) for char in text[0]]) f.write('\\par'.join([line[1] for line in dat]))