因此,我试图用python 3写一个简单的程序,该程序搜索文件并计算ive在列表中指定的特定单词的频率。但是,当我尝试将变量定义为文件时,出现NameError提示变量im正在尝试使用isnt defined。这可能是一个不好的解释,但这是我的代码和错误:
Traceback (most recent call last):
File "c:/Users/User/Desktop/School/COMP 1005 Code/Tutorials/Tut 5.py", line 26, in <module>
main()
File "c:/Users/User/Desktop/School/COMP 1005 Code/Tutorials/Tut 5.py", line 23, in main
count_stpwrds()
File "c:/Users/User/Desktop/School/COMP 1005 Code/Tutorials/Tut 5.py", line 10, in count_stpwrds
for line in f1:
NameError: name 'f1' is not defined
当我尝试在vscode中运行时,我得到:
{{1}}
有人可以向我解释我做错了什么吗?任何帮助将不胜感激!
答案 0 :(得分:1)
在两个函数中,f1
变量名已绑定到open
的返回值,但是当函数退出时,绑定将消失。这意味着f1
不“存在”于count_stpwrds()
中。
解决此问题的一种似乎简单的方法是将变量设置为全局变量,但我不会告诉您如何执行此操作,因为有一种更好的方法:-)
您应该做的只是从打开文件的函数中返回文件句柄,然后将其传递给需要它的函数,例如:
def file_write():
return open('Tutorial5.txt', 'w+')
def file_read():
return open('Tutorial5.txt', 'r')
def count_stpwrds(fileHandle):
# Blah blah blah
for line in fileHandle:
words = line.split()
# Blah blah blah
def main():
f1 = file_write()
f1 = file_read()
count_stpwrds(f1)