Slide 12
Slide 12 text
...
def output_results(word_freqs, outstream, count=10):
"""Output 10 most frequent words."""
for x in word_freqs[:count]:
outstream.write(str(x) + '\n')
def parse_args():
"""Parse arguments from the command line."""
parser = argparse.ArgumentParser("Count the frequency of words in text.")
parser.add_argument('-c', '--count', type=int, default=10,
help="Number of words to report. Default: 10")
parser.add_argument('infile', nargs="?", help="Source text. Default: STDIN")
parser.add_argument('outfile', nargs="?", help="Result destination. Default: STDOUT")
return parser.parse_args()
def main():
"""Main wordfreq function."""
...
if not args.outfile:
output_results(word_freqs, outstream=sys.stdout, count=args.count)
else:
with open(args.outfile, 'w') as outfile:
output_results(word_freqs, outstream=outfile, count=args.count)
...
Parameterize
number of words
./wordfreq.py -c 20 gettysburg.txt