无法识别UnboundLocalError变量

时间:2013-11-25 09:59:50

标签: python local-variables

我收到的错误是:UnboundLocalError: local variable 'words' referenced before assignment但我不确定原因。以下是我的代码:

def hasher(fname):
    try:
        with open(fname, 'r') as f:
            words = re.split('(["\'@&,;:\(\)\s+\*\?\.]|\w+)', f.read().lower())
    except:
        print 'Out'

    while '' in words:
        words.remove('')

但是当我尝试在while语句中引用单词时我收到错误,而我不确定原因。有帮助吗?谢谢!

1 个答案:

答案 0 :(得分:0)

您需要定义默认值

def hasher(fname):
    words = []
    try:
        with open(fname, 'r') as f:
            words = re.split('(["\'@&,;:\(\)\s+\*\?\.]|\w+)', f.read().lower())
    except:
        print 'Out'

    while '' in words:
        words.remove('')

    return words