Files

107 lines
4.0 KiB
Python
Executable File

#!/usr/bin/env python3
"""textstat — readability stats: sentences, average word length, estimated reading time.
Usage: textstat [FILE ...]
Reads stdin when no FILE is given. Words, sentences, characters, average word
and sentence length, Flesch reading ease, and reading time at 200 wpm — the
numbers an editor wants before deciding whether a draft is readable.
"""
import argparse, re, sys
WORD_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9'\-]*")
SENT_RE = re.compile(r"[^.!?]+[.!?]+")
VOWELS = "aeiouy"
def count_syllables(word):
word = word.lower().strip("'")
if not word:
return 0
n = 0
prev_vowel = False
for ch in word:
is_vowel = ch in VOWELS
if is_vowel and not prev_vowel:
n += 1
prev_vowel = is_vowel
if word.endswith("e") and n > 1:
n -= 1
return max(n, 1)
def stats(text):
words = WORD_RE.findall(text)
sentences = SENT_RE.findall(text)
n_words = len(words)
n_sent = len(sentences)
chars = sum(len(w) for w in words)
syllables = sum(count_syllables(w) for w in words)
avg_word = chars / n_words if n_words else 0
avg_sent = n_words / n_sent if n_sent else 0
flesch = 0.0
if n_words and n_sent:
flesch = 206.835 - 1.015 * (n_words / n_sent) - 84.6 * (syllables / n_words)
return {"words": n_words, "sentences": n_sent, "chars": chars,
"avg_word_len": avg_word, "avg_sent_len": avg_sent,
"syllables": syllables, "flesch": flesch,
"reading_minutes": n_words / 200.0}
def main(argv=None):
ap = argparse.ArgumentParser(prog="textstat",
description="Readability stats: sentences, average word length, estimated reading time.")
ap.add_argument("files", nargs="*", help="files to analyse (default: stdin)")
ap.add_argument("--selftest", action="store_true", help="run a built-in self-test and exit")
argv_list = list(argv) if argv is not None else sys.argv[1:]
if "--selftest" in argv_list:
return selftest()
a = ap.parse_args(argv)
if a.selftest:
return selftest()
texts = []
if a.files:
for f in a.files:
try:
with open(f, encoding="utf-8", errors="replace") as fh:
texts.append(fh.read())
except OSError as e:
print(f"textstat: {e}", file=sys.stderr)
return 1
else:
texts.append(sys.stdin.read())
total = {"words": 0, "sentences": 0, "chars": 0, "syllables": 0}
for text in texts:
s = stats(text)
for k in total:
total[k] += s[k]
n_words, n_sent = total["words"], total["sentences"]
flesch = 0.0
if n_words and n_sent:
flesch = 206.835 - 1.015 * (n_words / n_sent) - 84.6 * (total["syllables"] / n_words)
mins = n_words / 200.0
print(f"words: {n_words}")
print(f"sentences: {n_sent}")
print(f"characters: {total['chars']} (letters/digits in words)")
print(f"avg word length: {total['chars'] / n_words:.2f} chars" if n_words else "avg word length: -")
print(f"avg sentence: {n_words / n_sent:.1f} words" if n_sent else "avg sentence: -")
print(f"Flesch ease: {flesch:.1f} " + ("(very easy)" if flesch >= 90 else "(easy)" if flesch >= 80
else "(fairly easy)" if flesch >= 70 else "(standard)" if flesch >= 60 else "(fairly difficult)"
if flesch >= 50 else "(difficult)" if flesch >= 30 else "(very difficult)"))
print(f"reading time: {mins:.1f} min at 200 wpm"
+ (f" ({mins * 60:.0f} sec)" if mins < 1 else ""))
return 0
def selftest():
s = stats("The cat sat. The dog ran fast!")
assert s["words"] == 7 and s["sentences"] == 2, s
assert abs(s["avg_word_len"] - 22 / 7) < 0.01, s
assert abs(s["reading_minutes"] - 7 / 200) < 1e-9
assert stats("")["words"] == 0
assert count_syllables("hello") == 2 and count_syllables("cat") == 1
print("textstat selftest: PASS")
return 0
if __name__ == "__main__":
sys.exit(main())