답변

1

물론, 거기에 LR 파싱, 파서 combinators, 아마 다른 많은 kinds of parsers입니다.

+0

LL 파싱, 다양한 연산자 우선 구문 분석기, ... – EJP

1

실생활에서는 항상 재귀 적으로 구문을 구문 분석합니다. 파이썬에서

는 기본 알고리즘은 다음과 같습니다

import re 
import sys 

def toRpn(infixStr): 
    # divide string into tokens, and reverse so I can get them in order with pop() 
    tokens = re.split(r' *([\+\-\*\^/]) *', infixStr) 
    tokens = [t for t in reversed(tokens) if t!=''] 
    precs = {'+':0 , '-':0, '/':1, '*':1, '^':2} 

    #convert infix expression tokens to RPN, processing only 
    #operators above a given precedence 
    def toRpn2(tokens, minprec): 
     rpn = tokens.pop() 
     while len(tokens)>0: 
      prec = precs[tokens[-1]] 
      if prec<minprec: 
       break 
      op=tokens.pop() 

      # get the argument on the operator's right 
      # this will go to the end, or stop at an operator 
      # with precedence <= prec 
      arg2 = toRpn2(tokens,prec+1) 
      rpn += " " + arg2 + " " +op 
     return rpn 

    return toRpn2(tokens,0) 

print toRpn("5+3*4^2+1") 

#prints: 5 3 4 2^* + 1 + 

이 양식을 쉽게 할당 연산자처럼 오른쪽이 왼쪽 연결 괄호, 단항 연산자 및 연산자를 처리하도록되어있다.

위의 코드는 구문 오류를 적절히 처리하지 않습니다.

관련 문제