0

I am getting an error that says: UnboundLocalError: local variable 'words' referenced before assignment but I am unsure on why. The following is my code:

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('')

But I'm getting the error when I try to reference words in the while statement and I'm not sure on why. Any help? Thanks!

Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91
user1871869
  • 3,317
  • 13
  • 56
  • 106

1 Answers1

0

You need to define a default value,

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
Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91