Just to present an alternative way to Ryan's fine solution.
This is the sort of problem, where TeX beats Python hands down. TeX provides a method
to create control sequences automatically by using \csname...\endcsname. We leverage this to create a macro for each individual tag that will hold the list of sections that each tag contains.
I have assumed that you referring to tags in a similar fashion to those used in blogs on the web. We hold the tags in a list:
\tags{Mathematics,Biology,...,}
Each tag will have its own list, which will hold the section numbers, tagged with this particular tag,
\Art{1,5,6,7,8}
We define macros to tag a section in a similar fashion to \index by calling it as \tag{tag name}.
The MWE is shown below:
\documentclass{article}
\usepackage{lstdoc}
\makeatletter
\def\tags{Physics,Computer Science,Chemistry,}
%% sorts the tags for later on
\def\tags@sorted{\lst@BubbleSort\tags}
\tags@sorted
%% we automatically create macros for each tag
\def\macrofy@#1\@nil{%
\expandafter\def\csname#1\endcsname{}
}
\def\addtags#1{\g@addto@macro\tags{#1,}
\tags@sorted
\macrofy@@
}
%% Make macros to hold the lists for each tag
%%
\def\macrofy@@{\@for\next:=\tags\do{%
\expandafter\macrofy@\next\@nil
}}
\macrofy@@
\def\addtotag#1\@nil#2{%
\expandafter\ifx\csname#2\endcsname\@empty
\expandafter\g@addto@macro\csname#2\endcsname{#1}
\else
\expandafter\g@addto@macro\csname#2\endcsname{,#1}
\fi
}
\def\tag#1{%
\expandafter\addtotag\the\c@section\@nil{#1}
}
\def\thetags{%
%% we now print the tags or save them to a file
\section*{The Tags}
\@for\next:=\tags\do{%
\ifx\next\@empty\else\next: See Section(s) \@nameuse{\next}\par\fi
}
}
\parindent0pt
\begin{document}
% add some tags
\addtags{Mathematics,Art}
% test to see everything ok and list is sorted
\tags
% example text
\section{Einstein}
\tag{Physics}\tag{Mathematics}
\section{D E Knuth}
\tag{Computer Science}\tag{Art}
\section{Riemann}
\tag{Mathematics}
\section{Lamport}
\tag{Computer Science}
\section{Botticelli}
\tag{Art}
\section{Avogadro}
\tag{Chemistry}
%% prints the tags with the sections
\thetags
\end{document}
We define a command to print the tags (which we keep sorted) as \thetags. The lists are kept in memory and printed at the end. If we want to print them at the beginning of the document then we need to store them in a file, which we import. For brevity I omitted this as is trivial, and wanted to keep the code short and simple to read. It produces output as:
