Please critique my word frequency generator. I am a beginner programmer so any criticism are welcome.
Original Code: http://pastebin.com/rSRfbnCt
Here is my revised code after the feedback:
import string, time, webbrowser, collections, urllib2
def timefunc(function):
def wrapped(*args):
start = time.time()
data = function(*args)
end = time.time()
timetaken = end - start
print "Function: "+function.__name__+"\nTime taken:",timetaken
return data
return wrapped
@timefunc
def process_text(text_file):
words = text_file.read().lower().split()
words = [word.strip(string.punctuation+string.whitespace) for word in words]
words = [word for word in words if word]#skips ''(None) elements
return words
@timefunc
def create_freq_dict(wordlist):
freq_dict = collections.Counter(wordlist)
return freq_dict
@timefunc
def create_sorted_list(freqdict):
sorted_list = [(value,key) for key,value in list(freqdict.items())]#list() provides python 3 compatibility
sorted_list.sort(reverse=True)
return sorted_list
@timefunc
def write_results(sorted_list):
text_file = open('wordfreq.txt','w')
text_file.write('Word Frequency List\n\n')
rank = 0
for word in sorted_list:
rank += 1
write_str = "[{0}] {1:-<10}{2:->10}\n".format(rank, word[1],word[0])
text_file.write(write_str)
text_file.close()
## The Brothers Grimm
## This file can be obtained from Project Gutenberg:
## http://www.gutenberg.org/cache/epub/5314/pg5314.txt
web_file = urllib2.urlopen('http://www.gutenberg.org/cache/epub/5314/pg5314.txt')
wordlist = process_text(web_file)
freqdict = create_freq_dict(wordlist)
sorted_list = create_sorted_list(freqdict)
results = write_results(sorted_list)
webbrowser.open('wordfreq.txt')
print "END"