Jan-15-2019, 02:00 AM
Thank you @snippsat for your reply. I made the three corrections you suggested. I removed the has_key method. I replaced the instance of
When I execute the Python script in my unix shell, there is no traceback which is good. But now there is no output at all. Why? The shell just prompts me to enter another command.
The same thing happens when I run your much more elegant alternative, @snippsat. When I run
I figure the reason why will probably be pretty trivial and obvious once someone here clarifies. (I am ready to be hit over the head with a clue-bat. har har)
iteritems
with just items
. I removed the ’r’
parameter when invoking the open function. Having made these changes, my script now looks like this:#!/usr/bin/env python # encoding: utf-8 """ alice_file.py Created by Jason Elbourne on 2011-12-29. Copyright (c) 2011 Jason Elbourne. All rights reserved. """ import operator ## Get each word - Turn to Lower case (.lower()) ## Count Duplicates of words ## Dictionary {word:count,word2:count2} ## Sort this based on most used word ## Print the Top 20 Words def rank_words(f): """ Takes in a file, then ranks all the words within the file Args: a file Return: A sorted list of tuples """ word_dict = {} # Start with empty python Dictionary words = [] # Start with empty python List for line in f: list_of_words = line.split() for w in list_of_words: words.append(w.lower()) # Add Word to List for word in words: if word in word_dict: word_dict[word] += 1 # Incr. value in Dict. else: word_dict[word] = 1 # Add word and value to Dict. # This will sort the dictionary and return a list of Tuples return sorted(word_dict.items(), reverse=True, \ key=operator.itemgetter(1)) def main(): # Files f = open('Alice.txt') ranked_words_list = rank_words(f) f.close() # Print the results for w in list(ranked_words_list[:10]): print(w[0],"---", w[1]) if __name__ == '__main__': main()I’m expecting the output you shared.
When I execute the Python script in my unix shell, there is no traceback which is good. But now there is no output at all. Why? The shell just prompts me to enter another command.
The same thing happens when I run your much more elegant alternative, @snippsat. When I run
$ python pycounter.py
, nothing happens. Why? I figure the reason why will probably be pretty trivial and obvious once someone here clarifies. (I am ready to be hit over the head with a clue-bat. har har)