繁体   English   中英

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

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

我现在正在学习处理Python 3.6函数。 我尝试设置一个函数来计算特定单词在文本文件中出现的次数,但我遇到了NameError问题。

我尝试了pythontutor.com上的工具来可视化我的代码步骤以找出原因。 函数count_wordcount_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.

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