我正在尝试使用此wiki中的公式来实现一个返回文本的Flesch-Kincaid可读性测试的python函数:Flesch reading-ease test
我也遇到了一个与我所做的回答相同的问题:Converting Readability formula into python function
因此,通过使用此作为一种指南,我对我的实现采取了类似的方法,并以此作为我的代码结束:
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))
然后我运行了我的代码并收到了此错误消息:
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
与其他用户的帖子一样,我的目标是通过实现正确的功能来传递doctest。我也可以假设他/她与我在同一个编程班。
我对python有点新意,所以我不确定我做错了什么。