import datetime
from nltk_contrib import timex
now = datetime.date.today()
basedate = timex.Date(now.year, now.month, now.day)
print timex.ground(timex.tag("Hai i would like to go to mumbai 22nd of next month"), basedate)
print str(datetime.date.day)当我尝试运行上面的代码时,我得到了以下错误
File "/usr/local/lib/python2.7/dist-packages/nltk_contrib/timex.py", line 250, in ground
elif re.match(r'last ' + month, timex, re.IGNORECASE):
UnboundLocalError: local variable 'month' referenced before assignment我应该做些什么来纠正这个错误?
发布于 2017-05-22 07:35:43
timex模块有一个错误,即在ground函数中引用全局变量时不进行赋值。
要修复该错误,请添加以下代码,该代码应从第171行开始:
定义地面(tagged_text、base_date):
# Find all identified timex and put them into a list
timex_regex = re.compile(r'<TIMEX2>.*?</TIMEX2>', re.DOTALL)
timex_found = timex_regex.findall(tagged_text)
timex_found = map(lambda timex:re.sub(r'</?TIMEX2.*?>', '', timex), \
timex_found)
# Calculate the new date accordingly
for timex in timex_found:
global month # <--- here is the global reference assignment发布于 2019-11-28 04:31:42
当timex被连续多次调用时,上面关于将月添加为全局变量的解决方案会导致其他问题,因为除非您再次导入,否则变量不会重置。在AWS Lambda的部署环境中,这会发生在我身上。
一个不是很漂亮但不会造成问题的解决方案是在ground函数中再次设置Month值:
def ground(tagged_text, base_date):
# Find all identified timex and put them into a list
timex_regex = re.compile(r'<TIMEX2>.*?</TIMEX2>', re.DOTALL)
timex_found = timex_regex.findall(tagged_text)
timex_found = map(lambda timex:re.sub(r'</?TIMEX2.*?>', '', timex), \
timex_found)
# Calculate the new date accordingly
for timex in timex_found:
month = "(january|february|march|april|may|june|july|august|september| \
october|november|december)" # <--- reset month to the value it is set to upon importhttps://stackoverflow.com/questions/41850809
复制相似问题