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>First, </p>

<pre><code>import re
</code></pre>

<p>Then replace</p>

<pre><code>words = line.split(':')  
for word in words:
    counts[word] = counts.get(word,0) + 1
</code></pre>

<p>by</p>

<pre><code>line = re.search("[0-9]{2}:[0-9]{2}:[0-9]{2}", line).group(0)
words = line.split(':')
hour = words[0]
counts[hour] = counts.get(hour, 0) + 1
</code></pre>

<p>Input:</p>

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

<p>Output:</p>

<pre><code>09 4
12 3
15 1
13 1
</code></pre>

python split