#!/usr/bin/env python3 # # # Copyright (c) 2021, Hiroyuki Ohsaki. # All rights reserved. # # $Id: count.py,v 1.2 2021/11/15 10:35:18 ohsaki Exp $ # import sys def usage(): print(f"usage: {sys.argv[0]} string", file=sys.stderr) exit(1) def main(): # Extract the first argument. if len(sys.argv) <= 1: usage() astr = sys.argv[1] # Count the number of occurences. counts = {} for c in astr: # Dictionary element must be explicitly initialized. Otherwise, you can # use collections.defaultdict class. if c not in counts: counts[c] = 0 counts[c] += 1 # Display counts for every character. for c, n in counts.items(): print(c, n) if __name__ == "__main__": main()