I am trying to implement a python function that returns a Flesch-Kincaid readability test of a text by using this formula from this wiki: Flesch reading-ease test
I also came across a question with the same objective as I do that was answered: Converting Readability formula into python function
So by using this as a sort of guide I took a similar approach with my implementation and ended with this as my code:
import nltk
import collections
nltk.download('punkt')
nltk.download('gutenberg')
nltk.download('brown')
# DO NOT MODIFY THE CODE BELOW #
import re
VC = re.compile('[aeiou]+[^aeiou]+', re.I)
def count_syllables(word):
return len(VC.findall(word))
def compute_fres(text):
"""Return the FRES of a text.
>>> emma = nltk.corpus.gutenberg.raw('austen-emma.txt')
>>> compute_fres(emma) # doctest: +ELLIPSIS
99.40...
"""
tToken = nltk.word_tokenize(text)
for f in nltk.corpus.gutenberg.fileids():
nsents = len(nltk.corpus.gutenberg.sents(f))
nwords = len(nltk.corpus.gutenberg.words(f))
nsyllables = sum(count_syllables(w) for w in words)
fres = 206.835 - 1.015 * (nwords / nsents) - 84.6 * (nsyllables / nwords)
return len(fres.findall(tToken))
I then ran the my code and got this error message:
Error
**********************************************************************
File "C:/Users/WORLD/PycharmProjects/a1/a1.py", line 54, in a1.compute_fres
Failed example:
compute_fres(emma) # doctest: +ELLIPSIS
Exception raised:
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.4\helpers\pycharm\docrunner.py", line 140, in __run
compileflags, 1), test.globs)
File "<doctest a1.compute_fres[1]>", line 1, in <module>
compute_fres(emma) # doctest: +ELLIPSIS
File "C:/Users/WORLD/PycharmProjects/a1/a1.py", line 63, in compute_fres
nsyllables = sum(count_syllables(w) for w in words)
NameError: name 'words' is not defined
Like the other user's post, my goal is to pass the doctest by implementing the correct function. I can also assume that he/she is in the same programming class as me.
I'm a bit newby to python so I'm not sure what I'm doing wrong.