我收到的错误是: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语句中引用单词时我收到错误,而我不确定原因。有帮助吗?谢谢!
答案 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