首页 > 解决方案 > 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 这样的变量。

标签: pythoncommand-linenltkglobal

解决方案


向函数添加一些错误检查以帮助您调试:

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"

推荐阅读