Created
February 1, 2017 20:30
-
-
Save prune998/a3067fc83234303771a4f65013925e01 to your computer and use it in GitHub Desktop.
avec des class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import os | |
from pprint import pprint | |
class word_counter(): | |
def __init__(self): | |
print "starting the word counter Class" | |
def topwords(self,fileDesc,count): | |
counter = 0 | |
word_list = {} | |
for word in fileDesc.readline().split(): | |
counter += 1 | |
if word in word_list.keys(): | |
word_list[word] +=1 | |
else : | |
word_list[word] = 1 | |
top_words = sorted(word_list, key=word_list.__getitem__, reverse=True)[0:count] | |
final_list = {} | |
for word in top_words: | |
final_list[word] = word_list[word] | |
return final_list,counter | |
def display_words(self,word_list,display_type="text", ordered=False): | |
if ordered: | |
#word_list = sorted(word_list, key=word_list.__getitem__, reverse=True) | |
print "can't sort for now" | |
if display_type == "text": | |
# displaying as plain text | |
for word in word_list: | |
print ("word %s is used %d times" % (word, word_list[word])) | |
elif display_type == "json": | |
import json | |
print json.dumps(word_list) | |
else: | |
print "we can't display this" | |
def main(): | |
# the file to be opened - replace by command line argv | |
text_file = "text.txt" | |
count = 20 | |
with open("text.txt") as f: | |
first_test = word_counter() | |
word_list,total_count = first_test.topwords(f,count) | |
print ("Total word count is %d" % total_count) | |
first_test.display_words(word_list) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment