0

我是 python 编程的新手,我有一个挑战,我已经尝试了几天,但我似乎无法弄清楚我的代码有什么问题。我的代码获取一个文本文件,并告诉我文本中有多少个句子、单词和音节。除了我的代码将包含连续元音的音节计算为多个音节之外,我的一切都运行良好,我似乎无法弄清楚如何解决它。任何帮助将不胜感激。例如,如果文件有这样的内容:“或者拿起武器对抗麻烦的海洋,并通过反对结束他们?死:睡觉。” 它应该说文本有 21 个音节,但程序告诉我它有 26 个,因为它不止一次计算连续的元音。

fileName = input("Enter the file name: ")
inputFile = open(fileName, 'r')
text = inputFile.read()

# Count the sentences
sentences = text.count('.') + text.count('?') + \
            text.count(':') + text.count(';') + \
            text.count('!')

# Count the words
words = len(text.split())

# Count the syllables
syllables = 0
vowels = "aeiouAEIOU"
for word in text.split():
    for vowel in vowels:
        syllables += word.count(vowel)
    for ending in ['es', 'ed', 'e']:
        if word.endswith(ending):
            syllables -= 1
    if word.endswith('le'):
        syllables += 1

# Compute the Flesch Index and Grade Level
index = 206.835 - 1.015 * (words / sentences) - \
        84.6 * (syllables / words)
level = int(round(0.39 * (words / sentences) + 11.8 * \
                  (syllables / words) - 15.59))

# Output the results
print("The Flesch Index is", index)
print("The Grade Level Equivalent is", level)
print(sentences, "sentences")
print(words, "words")
print(syllables, "syllables") 
4

1 回答 1

1

我们可以遍历单词的字符,而不是计算每个单词的每个元音出现的次数,并且只计算一个元音,如果它前面没有另一个元音:

# Count the syllables
syllables = 0
vowels = "aeiou"
for word in (x.lower() for x in text.split()):
    syllables += word[0] in vowels
    for i in range(1, len(word)):
        syllables += word[i] in vowels and word[i - 1] not in vowels
    for ending in {'es', 'ed', 'e'}:
        if word.endswith(ending):
            syllables -= 1
    if word.endswith('le'):
        syllables += 1
于 2021-09-30T03:32:17.370 回答