You asked for Python, but I did it in C# because reasons.
Code
public class Program
{
static void Main(string[] args)
{
string line;
Tagger tagger = new Tagger();
var sr = new StreamReader("Input.txt");
while((line = sr.ReadLine()) != null)
{
tagger.AddTag(line);
tagger.TagText(line);
}
List<TaggedText> taggedText = tagger.GetTaggedText();
var textSetByTag = taggedText.GroupBy(t => t.Tag);
Console.WriteLine("Date: {0}", DateTime.Today.Date.ToShortDateString());
foreach(var textSet in textSetByTag)
{
Console.WriteLine();
Console.WriteLine("{0}:", textSet.Key.Label);
textSet.ToList().ForEach(t => Console.WriteLine("{0}", t.Text));
}
}
}
Code
public class Tagger
{
private List<Tag> _tags;
private List<TaggedText> _taggedText;
public Tagger()
{
_tags = new List<Tag>();
_taggedText = new List<TaggedText>();
}
public void TagText(string textToTag)
{
string regex = @"^(.*)\s*(/.*)$";
string[] matches = Regex.Split(textToTag, regex).Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();
if (matches.Length != 2)
return;
//extract tag
string text = matches[0].Trim();
string code = matches[1].Trim();
//check if tag exists
Tag tag = _tags.FirstOrDefault(t => t.Code.Equals(code));
//tag text
if(tag != null)
{
TaggedText taggedText = new TaggedText(tag, text);
_taggedText.Add(taggedText);
}
}
public void AddTag(string tagExpression)
{
string regex = @"^(/.*)\s*=\s*(.*)$";
//extract code and label
string[] matches = Regex.Split(tagExpression, regex).Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();
if (matches.Length != 2)
return;
string code = matches[0].Trim();
string label = matches[1].Trim();
Tag tag = new Tag(code, label);
_tags.Add(tag);
}
public List<TaggedText> GetTaggedText()
{
return new List<TaggedText>(_taggedText);
}
public List<Tag> GetTags()
{
return new List<Tag>(_tags);
}
}
Code
public class TaggedText
{
public TaggedText(Tag tag, string text)
{
if (tag == null)
throw new ArgumentNullException("tag");
Tag = tag;
Text = text;
}
public Tag Tag { get; private set; }
public string Text { get; private set; }
}
Code
public class Tag
{
public Tag(string code, string label)
{
if (string.IsNullOrWhiteSpace(code))
throw new ArgumentException("Code cannot be empty");
if (string.IsNullOrWhiteSpace(label))
throw new ArgumentException("Label cannot be empty");
Code = code;
Label = label;
}
public string Code { get; private set; }
public string Label { get; private set; }
}