简体   繁体   English

如何在 Python 3.6 中解决这个“NameError”问题?

[英]How to fix this 'NameError' problem in Python 3.6?

I'm learning to deal with function in Python 3.6 now.我现在正在学习处理Python 3.6函数。 I try to set a function to count the number of times a specific word appears in a text file, but I face the NameError problem.我尝试设置一个函数来计算特定单词在文本文件中出现的次数,但我遇到了NameError问题。

I tried the tool on pythontutor.com to visualise the steps of my code to find out why.我尝试了pythontutor.com上的工具来可视化我的代码步骤以找出原因。 It seems like the value of count_num in function count_word doesn't get pass to the for loop.函数count_wordcount_num的值似乎没有传递给 for 循环。 But I really don't understand why.但我真的不明白为什么。

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 + ".")

I expect the output would be "There are 89 'great' in The Wallypug in London.txt. But it just returns,我希望输出将是“伦敦.txt 的 The Wallypug 中有 89 个‘伟大的’。但它只是返回,

NameError: name 'count_num' is not defined

you're missing the assignment in this line你错过了这一行的任务

    count_word(filename, "great")

Change to改成

    count_num = count_word(filename, "great")

This might help :这可能有帮助:

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 + ".")

It's because count_num in function count_word is a local variable, and cannot be referenced in global area.这是因为count_num在功能count_word是一个局部变量,并不能在全球范围被引用。 Replace count_word(filename, "great") with count_num = count_word(filename, "great")更换count_word(filename, "great")count_num = count_word(filename, "great")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM