python - UnboundLocalError:赋值前引用的局部变量在命令行调用中不起作用
问题描述
我知道这类问题有很多解决方案。然而,他们似乎都对我的案子没有帮助。这是我指的代码:
from nltk.book import text4
def length_frequency(length):
'''
Parameter: length as an integer
'''
# finds words in given length
counter = 0
word_in_length = {}
for word in text4:
if len(word) == length and word not in word_in_length:
word_in_length[word] = text4.count(word)
for key in word_in_length:
if word_in_length[key] > counter:
max = word_in_length[key]
counter = max
max_word = key
print(f'The most frequent word with {length} characters is "{max_word}".\nIt occurs {counter} times.')
length_frequency(7)
Output:
The most frequent word with 7 characters is "country".
It occurs 312 times.
当我在 PyCharm 中尝试此代码时,它可以正常工作。但是,如果我通过命令行调用使用它,则会出现此错误:
Traceback (most recent call last):
File "program5.py", line 67, in <module>
main()
File "program5.py", line 60, in main
length_frequency(input_length)
File "program5.py", line 35, in length_frequency
print(f'The most frequent word with {length} characters is "{max_word[0]}".\nIt occurs {counter} times.')
UnboundLocalError: local variable 'max_word' referenced before assignment
当然,对于命令行调用,我导入 sys 并使用 sys.argv 作为长度参数。我曾尝试在函数开头添加全局 max_word,但它不起作用。在这个函数之前我没有分配像 max_word 这样的变量。
解决方案
向函数添加一些错误检查以帮助您调试:
def length_frequency(length: int) -> None:
'''
Parameter: length as an integer
'''
assert isinstance(length, int), f"{repr(length)} is not an int!"
word_counts = {word: text4.count(word) for word in set(text4) if len(word) == length}
assert word_counts, f"No words in corpus with length {length}!"
max_word = max(word_counts.keys(), key=word_counts.get)
print(f"The most frequent word with {length} characters is {max_word}")
(我稍微简化了实现,只是为了我自己的利益,使它更容易理解——我很确定它会做同样的事情而不会造成混淆。)
请注意,添加类型注释也意味着如果您有一行代码,例如:
length_frequency(sys.argv[1])
如果你要运行mypy
它会告诉你错误,assert
不需要:
test.py:19: error: Argument 1 to "length_frequency" has incompatible type "str"; expected "int"
推荐阅读
- android - 如何通过 USB 将命令从 android 发送到带有 windows 的 pc
- java - 我的 Android 功能区应用程序构建成功但无法运行
- c# - 如何编写带有缩进的阿拉伯语文本文件?
- java - 已安装 Java SE 开发工具包,但无法使用命令 javac
- cmd - 将每个名称相同的数千个文件移动到一个文件夹并重命名它们
- tfs - TFS 为运行任务构建自定义条件 - 检查特定的先前任务是否失败
- c++ - 将 C++ 程序内容重定向到 cmd.exe
- c# - JMeter 负载测试 C# Rest API - 大量采样时间
- c# - 是否可以访问 C# REST API 控制器中的非静态对象?
- c# - SqlDependency 无法正常工作 MVVM