Extract the year and the month from a line in a file and use a map to print every time its found to add 1 to the value
<pre><code>def Stats():
    file = open('mbox.txt')
    d = dict()
    for line in file:
        if line.startswith('From'):
            words = line.split()
            for words in file:
                key = words[3] + " " + words[6]
                if key:
                    d[key] +=1
    return d
</code></pre>

<p>The line reads</p>

<pre><code>From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008
</code></pre>

<p>I want to pull "Jan 2008" as the key   </p>

<p>My error message: </p>

<pre><code>Traceback (most recent call last):
  File "C:\Users\Robert\Documents\PYTHON WORKSPACE\Program 1.py", line 78, in &lt;module&gt;
  File "C:\Users\Robert\Documents\PYTHON WORKSPACE\Program 1.py", line 76, in &lt;module&gt;
  File "C:\Users\Robert\Documents\PYTHON WORKSPACE\Program 1.py", line 63, in &lt;module&gt;
builtins.KeyError: 'u -'
</code></pre>

<p>Not the direct answer to the question, but a possible alternative solution - use the <a href="https://labix.org/python-dateutil" rel="nofollow"><code>dateutil</code></a> datetime parser in a "fuzzy" mode and simply format the extracted <code>datetime</code> object via <a href="https://docs.python.org/2/library/datetime.html#datetime.datetime.strftime" rel="nofollow"><code>.strftime()</code></a>:</p>

<pre><code>In [1]: from dateutil.parser import parse

In [2]: s = "From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008"

In [3]: parse(s, fuzzy=True).strftime("%b %Y")
Out[3]: 'Jan 2008'
</code></pre>

python python-2.7 python-3.x