在方法中使用命令行中的参数

问题描述 投票:0回答:1

编码脚本以将字符串输入匹配到不确定的有限自动机,并且我希望能够从命令行中获取字符串,例如

python regex.py -nfa a.b|c -string ab
Result: True

但是当我尝试出现错误时

追踪(最近一次通话):文件“ regex.py”,第144行,在print(“结果:”,格式(match(str(args ['nfa']),str(args ['string']))))TypeError:“命名空间”对象不是可下标

发生错误的代码在这里:

    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument("-nfa", required=True, help="NFA",type=str)
    parser.add_argument("-string", required=True, help="String to match to nfa",type=str)
    parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS, help='Default Help Message of Project Command line')
    args = parser.parse_args()
    print(" Result:", match(str(args['nfa']), str(args['string'])))

Match():

def match(regex, s):
    """Match a string to an NFA"""
    #this function will return true if and only if the regular expression
    #regex (fully) matches the string s. It returns false otherwise

    #compile the regular expression into nfa
    nfa = compile(regex)

    # try to match the regular expression to the string s.
    #the current set of states
    current = set()
    #add the first state, and follow all of epsilon arrows
    followEs(nfa.start, current)
    #the previuos set of states
    previous = set()
    #loop through characters in s
    for c in s:
        previous = current
        #creat a new empty set for states we're about to be in
        current = set()
        #loop through the previous states
        for state in previous:
            #only follow arrows not labeled by E (epsilon)
            if state.label is not None:
                #if the label of the state is = to the character we've read
                if state.label == c:
                    #add the state(s) at the end of the arrow to current.
                   followEs(state.edges[0], current)
    #ask the nfa if it matches the string s.
    return nfa.accept in current    

compile():

def compile(infix):
    """Return Fragment of NFA that represents infix regex"""
    #convert infix to postfix
    postfix = shunting.shunt(infix)
    #make a listfix stack of chars and invert it
    postfix=list(postfix)[::-1] 
    #stack for nfa fragments
    nfa_stack = []
    while(postfix):
        #pop character from postfix
        c= postfix.pop()
        if(c=='.'):#pop two frags off stack
            frag1=nfa_stack.pop()
            frag2=nfa_stack.pop()
            #point from end of frag2 to start of frag1
            frag2.accept.edges.append(frag1.start)
            #frag2's start state is new start state
            start = frag2.start
            #frag1s new accept state 
            accept = frag1.accept
        elif(c=='|' ):
            #pop 2 frags off stack
            frag1=nfa_stack.pop()
            frag2=nfa_stack.pop()
            #create new start and accept states
            accept = State()
            start= State(edges=[frag2.start,frag1.start])
            #point old accept states at new one
            frag2.accept.edges.append(accept)
            frag1.accept.edges.append(accept)
        elif(c=='*'):
            #pop single fragment off stack
             frag= nfa_stack.pop()
             #create new start and accept state
             accept = State()
             #point arrows i
             start= State(edges=[frag.start,accept])
             frag.accept.edges=[frag.start,accept]     
        else:
            accept = State()
            start = State(label=c,edges=[accept])
        #create new instance of fragment to represent the new nfa
        newfrag = Fragment(start,accept)
        #push new nfa to stack
        nfa_stack.append(newfrag)
    #the nfa stack should have exactly one nfa one it -  the answer
    return nfa_stack.pop()
python command-line-arguments argparse
1个回答
0
投票

argsNamespace对象,而不是dictionary

您应该访问作为属性提供的参数:args.arg1, args.arg2, etc..

因此更改:

print(" Result:", match(str(args['nfa']), str(args['string'])))

至:

print(" Result:", match(str(args.nfa), str(args.string)))

如果要将args转换为字典,则可以执行:

args_as_dict = {key: value for key, value in vars(parser.parse_args()).items()}
print(args_as_dict['nfa'], args_as_dict['string'])
© www.soinside.com 2019 - 2024. All rights reserved.