Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 输入验证&;字符串转换_Python - Fatal编程技术网

Python 输入验证&;字符串转换

Python 输入验证&;字符串转换,python,Python,我有一个脚本,它从用户那里获取输入,我想先验证输入,然后将用户输入转换为预定义的格式。输入应如下所示: my_script-c'格式日期(%d/%m)==23/5&&userName==John Dee&&status==c 目前我只处理formatDate()bit。主要规则是: 年、月、日的格式字符串可以是任意顺序 如果缺少m[或y或d],将使用当前_月添加;其他人也一样 格式字符串和值必须使用相同的分隔符 键和值必须用== 不同的约束必须用&& 允许单个或多个约束 因此,对于给定的示例

我有一个脚本,它从用户那里获取输入,我想先验证输入,然后将用户输入转换为预定义的格式。输入应如下所示:

my_script-c'格式日期(%d/%m)==23/5&&userName==John Dee&&status==c

目前我只处理
formatDate()
bit。主要规则是:

  • 年、月、日的格式字符串可以是任意顺序
  • 如果缺少m[或y或d],将使用当前_月添加;其他人也一样
  • 格式字符串和值必须使用相同的分隔符
  • 键和值必须用
    ==
  • 不同的约束必须用
    &&
  • 允许单个或多个约束
因此,对于给定的示例,它应该返回
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')
#/usr/bin/env python
#
导入系统,re
从时间导入本地时间,strftime
theDy=strftime(“%d”,localtime())
theMn=strftime(“%m”,localtime())
theYr=strftime(“%Y”,localtime())
def主(arg):
打印“输入字符串:%s”%arg
arg=”“.join(arg.split()).lower()
如果arg.startswith('=')或re.search('==',arg)或“==”不在arg中:
sys.exit(“无效的查询字符串!”)
else:my_arg=arg.split(“&&&”)
c_dict={}
对于范围内的ix(len(my_arg)):
LL=my_arg[ix]。拆分('=')
#LL=dict(zip(LL[:-1:2],LL[1:2]))
#不要添加重复的密钥
如果没有c_dict.has_key(LL[0]):
c_dict[LL[0]]=LL[1]
对于k,v在已排序(c_dict.items())中:
如果k.startswith('formattate'):
ymd=re.sub(r'[(,)]','',k).替换('formatdate','')
ymd=(str(ymd).strip()).split('/'))

如果len(ymd)您没有制造麻烦,但是您是否考虑过扩展用户请求语法的后果


最简单的解析器是。您可以将其应用于用户请求并轻松扩展语法。您可以找到Python实现。

还有一个问题:有人知道如何编写一个ReExp,它将匹配唯一的模式
20110512
20110512-12
?对于第一种类型,我只做了:
re.compile('20/d/d[01]/d[0123]/d$)
如何包括第二种类型?干杯嗯,我觉得你的正则表达式错了。要以第一种格式匹配日期,请使用:(201[0 | 1])(0[1-9]| 1[012])(0[1-9]|[12][0-9]| 3[01])。顺便说一句,试试“kodos”程序,它是测试regexp的一个很好的工具,它是用Python+PyQt3编写的。我用另一种方式键入了斜杠<代码>重新编译('20\d\d[01]\d[0123]\d$)
工作正常。但你的答案更准确。干杯