我有一个脚本,它从用户那里获取输入,我想先验证输入,然后将用户输入转换为预定义的格式。输入应该是这样的:
my_script -c 'formatDate(%d/%m) == 23/5 && userName == John Dee && status == c
目前我只处理formatDate()
位。主要规则是:
year,month,day
的格式字符串可以按任意顺序current_month
添加; ==
&&
因此,对于给定的示例,它应该返回20110523
作为有效约束。经过一些工作,这就是我想出来的,这非常有效:
#!/usr/bin/env python
#
import sys, re
from time import localtime, strftime
theDy = strftime('%d', localtime())
theMn = strftime('%m', localtime())
theYr = strftime('%Y', localtime())
def main(arg):
print "input string: %s" % arg
arg = "".join(arg.split()).lower()
if arg.startswith('=') or re.search('===', arg) or "==" not in arg:
sys.exit("Invalid query string!")
else: my_arg = arg.split('&&')
c_dict = {}
for ix in range(len(my_arg)):
LL = my_arg[ix].split('==')
#LL = dict(zip(LL[:-1:2], LL[1::2]))
# don't add duplicate key
if not c_dict.has_key(LL[0]):
c_dict[LL[0]] = LL[1]
for k,v in sorted(c_dict.items()):
if k.startswith('formatdate') :
ymd = re.sub(r'[(,)]', ' ', k).replace('formatdate','')
ymd = (str(ymd).strip()).split('/')
if len(ymd) <= 3 and len(ymd) == len(v.split('/')):
d_dict = dict(zip(ymd, v.split('/')))
if not d_dict.has_key('%y'):
d_dict['%y'] = theYr
if not d_dict.has_key('%m'):
d_dict['%m'] = theMn
if not d_dict.has_key('%d'):
d_dict['%d'] = theDy
else: sys.exit('date format mismatched!!')
Y = d_dict['%y'];
if d_dict['%m'].isdigit() and int(d_dict['%m']) <=12:
M = d_dict['%m'].zfill(2)
else: sys.exit("\"Month\" is not numeric or out of range.\nExiting...\n")
if d_dict['%d'].isdigit() and int(d_dict['%d']) <=31:
D = d_dict['%d'].zfill(2)
else: sys.exit("\"Day\" is not numeric or out of range.\nExiting...\n")
# next line needed for future use
fmtFile = re.compile('%s%s%s' % (Y,M,D))
print "file_name is: %s" % Y+M+D
if __name__ == "__main__":
main('formatDate(%d/%m)== 23/5')
我的问题是:
感谢您的时间。干杯!!
答案 0 :(得分:1)
您没有制作复杂功能,但是您是否想过扩展用户请求语法的后果?
最简单的解析器是Shunting yard algorithm。您可以将其用于用户请求并轻松扩展语法。您可以找到Python实现here。