Selecting text using multiple splits
<p>I've started to learn python and am stuck on an assignment regarding manipulating text data. An example of the text lines I need to manipulate:</p>

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

<p>I need to extract the hours from each line (in this case 09) and then find the most common hours the emails were sent.</p>

<p>Basically, what I need to do is build a for loop that splits each text by colon</p>

<pre><code>split(':')
</code></pre>

<p>and then splits by space:</p>

<pre><code>split()
</code></pre>

<p>I've tried for hours, but can't seem to figure it out. What my code looks like so far:</p>

<pre><code>name = raw_input("Enter file:")
if len(name) &lt; 1 : name = "mbox-short.txt"
handle = open(name)
counts = dict()
lst = list()
temp = list()
for line in handle:
    if not "From " in line: continue
    words = line.split(':')  
    for word in words:
        counts[word] = counts.get(word,0) + 1

for key, val in counts.items():
    lst.append( (val, key) )
lst.sort(reverse = True)

for val, key in lst:
print key, val
</code></pre>

<p>The code above only does 1 split, but I've kept trying multiple methods to split the text again. I keep getting a list attribute error, saying "list object has no attribute split". Would appreciate any help on this. Thanks again</p>

<p>Using the same test file as Marcel Jacques Machado:</p>

<pre><code>&gt;&gt;&gt; from collections import Counter
&gt;&gt;&gt; Counter(line.split(' ')[-2].split(':')[0] for line in open('input')).items()
[('12', 3), ('09', 4), ('15', 1), ('13', 1)]
</code></pre>

<p>This shows that <code>09</code> occurs 4 times while <code>13</code> occurs only once.</p>

<p>If we want prettier output, we can do some formatting.  This shows the hours and their counts sorted from most common to least common:</p>

<pre><code>&gt;&gt;&gt; print('\n'.join('{} {}'.format(hh, n) for hh,n in Counter(line.split(' ')[-2].split(':')[0] for line in open('input')).most_common()))
09 4
12 3
15 1
13 1
</code></pre>

python split