[英]How to fix this 'NameError' problem in Python 3.6?
我现在正在学习处理Python 3.6
函数。 我尝试设置一个函数来计算特定单词在文本文件中出现的次数,但我遇到了NameError
问题。
我尝试了pythontutor.com
上的工具来可视化我的代码步骤以找出原因。 函数count_word
中count_num
的值似乎没有传递给 for 循环。 但我真的不明白为什么。
filenames = [
"The Wallypug in London.txt",
"Chats on Old Silver.txt",
"Jack Jingle, and Sucky Shingle.txt",
"Superstition and Force.txt"
]
def count_word(filename, word):
with open(filename) as open_file:
file_content = open_file.read()
count_num = file_content.lower().count(word)
return count_num
for filename in filenames:
count_word(filename, "great")
print('There are ' + str(count_num) + " 'great' in " + filename + ".")
我希望输出将是“伦敦.txt 的 The Wallypug 中有 89 个‘伟大的’。但它只是返回,
NameError: name 'count_num' is not defined
你错过了这一行的任务
count_word(filename, "great")
改成
count_num = count_word(filename, "great")
这可能有帮助:
filenames = [
"The Wallypug in London.txt",
"Chats on Old Silver.txt",
"Jack Jingle, and Sucky Shingle.txt",
"Superstition and Force.txt"
]
count_num ="" #define count_num here
def count_word(filename, word):
count_num=0
return count_num
for filename in filenames:
count_word(filename, "great")
print('There are ' + str(count_num) + " 'great' in " + filename + ".")
这是因为count_num
在功能count_word
是一个局部变量,并不能在全球范围被引用。 更换count_word(filename, "great")
与count_num = count_word(filename, "great")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.