Created
February 28, 2017 09:36
-
-
Save alexwlchan/8a862a15941ff58cf17c6bf54fc771a0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
# -*- encoding: utf-8 -*- | |
"""Returns a human-friendly word count of the string passed to stdin. | |
Example outputs: | |
* 5 words | |
* 100 words | |
* 1.5k words | |
* 10k words | |
""" | |
import subprocess | |
import sys | |
def count_words(string): | |
"""Count the number of words in a string.""" | |
proc = subprocess.Popen(['wc', '-w'], | |
stdout=subprocess.PIPE, | |
stdin=subprocess.PIPE, | |
stderr=subprocess.STDOUT) | |
stdout, _ = proc.communicate(input=string) | |
return int(stdout.decode()) | |
def summarise_count(count): | |
"""Turn a number into a human-friendly word count.""" | |
assert count >= 0 | |
if count == 1: | |
return '1 word' | |
elif count < 1000: | |
return '%d words' % count | |
else: | |
prefix = str(round(count / 1000, ndigits=1)) | |
if prefix.endswith('.0'): | |
return '%dk words' % int(prefix[:-2]) | |
else: | |
return '%sk words' % prefix | |
if __name__ == '__main__': | |
sys.stdout.write(summarise_count(count_words(sys.stdin.read()))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment