Skip to content

Instantly share code, notes, and snippets.

@henriquebastos
Created March 28, 2019 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save henriquebastos/bc1ec70af6af3ef9cb0282c5c78cdaaa to your computer and use it in GitHub Desktop.
Save henriquebastos/bc1ec70af6af3ef9cb0282c5c78cdaaa to your computer and use it in GitHub Desktop.
wordcount.py
#!/usr/bin/python -tt
import argparse
import re
from collections import Counter
def read(f):
return re.split(r'\W+', f.read().lower())
def asc(counter):
return sorted(counter.items())
def top(counter, limit=20):
return sorted(counter.items(), key=lambda t: t[-1], reverse=True)[:limit]
def report(words):
return '\n'.join([f'{w:<10}: {c:>02}' for w, c in words])
def count_words(filename):
return report(asc(Counter(read(filename))))
def top_words(filename):
return report(top(Counter(read(filename))))
def cli():
parser = argparse.ArgumentParser(prog='wordcount', description='Count all the words!')
parser.add_argument('filename', type=argparse.FileType(), help='File to be counted.')
parser.add_argument('--topcount', '-t', dest='operation', action='store_const',
const=top_words, default=count_words, help='Count and show top 20 occurencies.')
args = parser.parse_args()
print(args.operation(args.filename))
if __name__ == '__main__':
# cli()
import tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.hi_there = tk.Button(self)
self.hi_there["text"] = "Hello World\n(click me)"
self.hi_there["command"] = self.say_hi
self.hi_there.pack(side="top")
self.quit = tk.Button(self, text="QUIT", fg="red",
command=self.master.destroy)
self.quit.pack(side="bottom")
def say_hi(self):
print("hi there, everyone!")
root = tk.Tk()
app = Application(master=root)
app.mainloop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment