【发布时间】:2019-05-27 05:54:55
【问题描述】:
Traceback (most recent call last):
File "C:\Users\Owner\AppData\Local\Programs\Python\Python37-32\ch6\analyze.py", line 46, in <module>
words = text.split()
NameError: name 'text' is not defined
我已经检查了我的代码,以确保我按照我所关注的书的状态输入它。我正在努力学习 Head First Learn to Code。一切似乎都应该如此。我不知道为什么我的代码总是抛出这个错误。
import ch1text
def count_syllables(words):
count = 0
for word in words:
word_count = count_syllables_in_word(word)
count = count + word_count
return count
def count_syllables_in_word(word):
count = 0
if len(word) <= 3:
return 1
vowels = "aeiouAEIOU"
prev_char_was_vowel = False
for char in word:
if char in vowels:
if not prev_char_was_vowel:
count = count + 1
prev_char_was_vowel = True
else:
prev_char_was_vowel = False
return count
def count_sentences(text):
count = 0
for char in text:
if char == '.' or char == ';' or char == '?' or char == '!':
count = count + 1
return count
def compute_readability(text):
total_words = 0
total_sentences = 0
total_syllables = 0
score = 0
words = text.split()
total_words = len(words)
total_sentences = count_sentences(text)
total_syllables = count_syllables(words)
print(total_words, 'words')
print(total_sentences, 'sentences')
print(total_syllables, 'syllables')
compute_readability(ch1text.text)
还有一个文本文件,它最初是一个 ch1text.txt 文件,我被告知在 Python 中打开它,然后在将其导入 Python 之前将其保存为 ch1text.py。当我运行 ch1text.py 文件时,它会运行文本。我期待的是另一个代码来阅读我导入的文本并告诉我 ch1text.py 中有多少单词、句子和音节。相反,我收到错误消息说未定义文本。请帮我。我花了很长时间试图自己解决这个问题,并且在我明白自己哪里出错之前我觉得我无法继续前进。
*使用适当的缩进进行编辑,以反映我在 py 文档中的内容。
【问题讨论】:
-
请修正缩进。 Python 中的缩进是一个句法 特性。您发布的代码有许多语法错误,其中一些可能是您看到的错误的原因。