Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/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