Parsing chat messages as config
<p>I'm trying write a function that would be able to parse out a file with defined messages for a set of replies but am at loss on how to do so.</p>

<p>For example the config file would look:</p>

<pre><code>[Message 1]
1: Hey
   How are you?
2: Good, today is a good day.
3: What do you have planned?
   Anything special?
4: I am busy working, so nothing in particular.
   My calendar is full.
</code></pre>

<p>Each new line without a number preceding it is considered part of the reply, just another message in the conversation without waiting for a response.</p>

<p>Thanks</p>

<p>Edit: The config file will contain multiple messages and I would like to have the ability to randomly select from them all. Maybe store each reply from a conversation as a list, then the replies with extra messages can carry the newline then just split them by the newline. I'm not really sure what would be the best operation.</p>

<p><strong>Update:</strong></p>

<p>I've got for the most part this coded up so far:</p>

<pre><code>def parseMessages(filename):
  messages = {}
  begin_message = lambda x: re.match(r'^(\d)\: (.+)', x)
  with open(filename) as f:
    for line in f:
      m = re.match(r'^\[(.+)\]$', line)
      if m:
        index = m.group(1)
      elif begin_message(line):
        begin = begin_message(line).group(2)
      else:
        cont = line.strip()
    else:
      # ??
  return messages
</code></pre>

<p>But now I am stuck on being able to store them into the dict the way I'd like..</p>

<p>How would I get this to store a dict like:</p>

<pre><code>{'Message 1': 
  {'1': 'How are you?\nHow are you?', 
   '2': 'Good, today is a good day.', 
   '3': 'What do you have planned?\nAnything special?', 
   '4': 'I am busy working, so nothing in particular.\nMy calendar is full'
  }  
}
</code></pre>

<p>Or if anyone has a better idea, I'm open for suggestions.</p>

<p>Once again, thanks.</p>

<p><strong>Update Two</strong></p>

<p>Here is my final code:</p>

<pre><code>import re
def parseMessages(filename):
  all_messages = {}
  num = None
  begin_message = lambda x: re.match(r'^(\d)\: (.+)', x)
  with open(filename) as f:
    messages = {}
    message = []
    for line in f:
      m = re.match(r'^\[(.+)\]$', line)
      if m:
        index = m.group(1)
      elif begin_message(line):
        if num:
          messages.update({num: '\n'.join(message)})
        all_messages.update({index: messages})
        del message[:]
        num = int(begin_message(line).group(1))
        begin = begin_message(line).group(2)
        message.append(begin)
      else:
        cont = line.strip()
        if cont:
          message.append(cont)
    return all_messages
</code></pre>
