Skip to content

Instantly share code, notes, and snippets.

@az09
Created September 28, 2016 09:43
Show Gist options
  • Save az09/0b1cb08230abe2671a54e468582f93fe to your computer and use it in GitHub Desktop.
Save az09/0b1cb08230abe2671a54e468582f93fe to your computer and use it in GitHub Desktop.
# Standard Opening - open and read target input text file.
file = raw_input('Enter file name: ')
if len(file) < 1 : file = 'mbox-short.txt'
try :
fhand = open(file)
except :
print 'Cannot open file: ', file, '.', '...please try, again.'
exit ()
# Prime the dictionary
counts = dict()
# Compute dictionary to map each word to the count of words
for line in fhand :
if not line.startswith('From ') : continue
words = line.split()
words = words[1]
counts[words] = counts.get(words, 0) + 1
# Construct a list of (val, key) tuples
lst = list() # note: 'lst' begins with lowercase letter 'L'
for key, val in counts.items() :
lst.append( (val, key)) # important to note that we are switching the order (key, val) to (val, key)
# Sort the tuples list in reverse order
lst.sort(reverse=True)
# Assign tuple in (val, key) order to variables and print in swapped (key, value) order
val, key = lst[0]
print key, val
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment