UnboundLocalError: local variable referenced before assignment doesn't work in command line call

UnboundLocalError: local variable referenced before assignment doesn't work in command line call

我知道有很多解决这类问题的方法。但是,其中 none 似乎对我的案件有所帮助。这是我指的代码:

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 作为长度参数。我试过在函数的开头添加 global 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"