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中打开它,然后将其另存为ch1text.py,然后再将其导入Python。当我运行ch1text.py文件时,它确实在运行文本。我期望的是其他代码可以读取我导入的文本,并告诉我ch1text.py中有多少个单词,句子和音节。相反,我收到错误消息,指出未定义文本。请帮我。我花了很长时间试图独自解决这个问题,并且直到我了解自己要去哪里的时候才觉得自己可以前进。
*使用适当的缩进进行编辑以反映我的py文档中的内容。
答案 0 :(得分:0)
在Python中,缩进用于determine the grouping of statements。
您可能只需要缩进显示在下面的所有行:
def compute_readability(text):
答案 1 :(得分:0)
问题出在函数调用上。在您编写的代码中,
words = text.split() <--
total_words = len(words)
total_sentences = count_sentences(text) <--
如果您仔细观察,则text不是传递给text.split或count_sentences的全局变量。因此,您需要修复它。您只能拆分存在的东西,在这种情况下不存在。