我正在学习处理Python 3.6
中的函数。我尝试设置一个函数来计算特定单词在文本文件中出现的次数,但是我遇到了NameError
问题。
我在pythontutor.com
上尝试了该工具,以可视化代码步骤来找出原因。函数count_num
中count_word
的值似乎没有传递给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 + ".")
我希望输出为“ London.txt中的Wallypug中有89个'great'。但是它只是返回,
NameError: name 'count_num' is not defined
答案 0 :(得分:1)
您在此行中缺少作业
count_word(filename, "great")
更改为
count_num = count_word(filename, "great")
答案 1 :(得分:0)
这可能有帮助:
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 + ".")
答案 2 :(得分:0)
这是因为函数count_num
中的count_word
是局部变量,不能在全局区域中引用。
将count_word(filename, "great")
替换为count_num = count_word(filename, "great")