2014年7月28日 星期一

Dictionary using

name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
counts = dict()
lines = ''
words = list()
for line in handle:
    line = line.rstrip()
    if line.startswith('From:'):
        line = line.split()
        lines += line[1] + ' ' # Add only all emails to lines, get rid of From:
words = lines.split()
for word in words:
    counts[word] = counts.get(word,0) + 1  # Create dict and count at the same time.
print counts  
bigcount = None
bigword = None
for word,count in counts.items():
    if bigcount == None or count > bigcount:
        bigword = word
        bigcount = count
print bigword + ' ' + str(bigcount)
     

Output:
cwen@iupui.edu 5

2014年7月26日 星期六

Parse file

fname = raw_input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"

fh = open(fname)
count = 0
for line in fh:
    line = line.rstrip(
    if line.startswith('From:'):
        line = line.split()
        print line[1]
        count += 1
   
print "There were", count, "lines in the file with From as the first word"

Output:
stephen.marquard@uct.ac.za
louis@media.berkeley.edu
zqian@umich.edu
rjlowe@iupui.edu
zqian@umich.edu
rjlowe@iupui.edu
cwen@iupui.edu
cwen@iupui.edu
gsilver@umich.edu
gsilver@umich.edu
zqian@umich.edu
gsilver@umich.edu
wagnermr@iupui.edu
zqian@umich.edu
antranig@caret.cam.ac.uk
gopal.ramasammycook@gmail.com
david.horwitz@uct.ac.za
david.horwitz@uct.ac.za
david.horwitz@uct.ac.za
david.horwitz@uct.ac.za
stephen.marquard@uct.ac.za
louis@media.berkeley.edu
louis@media.berkeley.edu
ray@media.berkeley.edu
cwen@iupui.edu
cwen@iupui.edu
cwen@iupui.edu
There were 27 lines in the file with From as the first word