在Udacity学习Python时调用check_profanity出现NameError的原因
问题分析与修复方案
嘿,我来帮你拆解下代码里的问题,这就是你遇到NameError和潜在bug的根源:
1. 函数调用顺序搞反了
你在定义check_profanity函数之前就直接调用了read_text(),而read_text()内部又会调用check_profanity。Python是逐行解释执行的,当执行到read_text()时,check_profanity还没被加载进解释器,自然就会抛出NameError说找不到这个函数。
2. check_profanity内部的参数使用错误
你写了text_to_check = read_text.contents_of_file,这完全是误用:
read_text是个普通函数,不是类实例或对象,根本没有contents_of_file这个属性- 函数已经通过参数拿到了
contents_of_file,直接用这个参数名就行
修正后的完整代码
import urllib def read_text(): quotes = open("C:\\Udacity Python\\Lesson 4\\movie_quotes.txt", "r") contents = quotes.read() print(contents) quotes.close() check_profanity(contents) def check_profanity(contents_of_file): text_to_check = contents_of_file # 直接使用传入的参数 connection = urllib.urlopen("http://www.wdylike.appspot.com/?q="+text_to_check) output = connection.read() print(output) # 补全你没写完的打印语句 connection.close() # 记得关闭网络连接,避免资源泄漏 # 把函数调用放到所有函数定义之后,确保解释器先加载所有函数 read_text()
额外给个小优化建议:处理文件时用with语句更安全,它会自动帮你关闭文件,不用手动调用close():
def read_text(): with open("C:\\Udacity Python\\Lesson 4\\movie_quotes.txt", "r") as quotes: contents = quotes.read() print(contents) check_profanity(contents)
内容的提问来源于stack exchange,提问作者Tom Brittenden
相关产品推荐
相关产品推荐

