当前位置: 首页>>代码示例>>Python>>正文


Python Scanner.newtext方法代码示例

本文整理汇总了Python中scanner.Scanner.newtext方法的典型用法代码示例。如果您正苦于以下问题:Python Scanner.newtext方法的具体用法?Python Scanner.newtext怎么用?Python Scanner.newtext使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在scanner.Scanner的用法示例。


在下文中一共展示了Scanner.newtext方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: from scanner import Scanner [as 别名]
# 或者: from scanner.Scanner import newtext [as 别名]
class Parser:
    def __init__(self, text=''):
        self.lex     = Scanner(text)           # make a scanner
        self.vars    = {'pi':3.14159}          # add constants
        self.traceme = TraceDefault
 
    def parse(self, *text):                    # external interface
        if text: 
            self.lex.newtext(text[0])          # reuse with new text
        tree = self.analyse()                  # parse string
        if tree:
            if self.traceme:                   # dump parse-tree?
                print; tree.trace(0)
            if self.errorCheck(tree):          # check names
                self.interpret(tree)           # evaluate tree

    def analyse(self):
        try:
            self.lex.scan()                    # get first token
            return self.Goal()                 # build a parse-tree
        except SyntaxError:
            print 'Syntax Error at column:', self.lex.start
            self.lex.showerror()
        except LexicalError:
            print 'Lexical Error at column:', self.lex.start
            self.lex.showerror()

    def errorCheck(self, tree):
        try:
            tree.validate(self.vars)           # error checker
            return 'ok'
        except UndefinedError, varinfo:
            print "'%s' is undefined at column: %d" % varinfo
            self.lex.start = varinfo[1]
            self.lex.showerror()               # returns None 
开发者ID:inteljack,项目名称:EL6183-Digital-Signal-Processing-Lab-2015-Fall,代码行数:37,代码来源:parser2.py

示例2: __init__

# 需要导入模块: from scanner import Scanner [as 别名]
# 或者: from scanner.Scanner import newtext [as 别名]
class Parser:
    def __init__(self, text=''):
        self.lex  = Scanner(text)              # embed a scanner
        self.vars = {'pi':3.14159}             # add a variable

    def parse(self, *text):
        if text:                               # main entry-point
            self.lex.newtext(text[0])          # reuse this parser?
        try:
            self.lex.scan()                    # get first token
            self.Goal()                        # parse a sentence
        except SyntaxError:
            print 'Syntax Error at column:', self.lex.start
            self.lex.showerror()
        except LexicalError:
            print 'Lexical Error at column:', self.lex.start
            self.lex.showerror()
        except UndefinedError, name:
            print "'%s' is undefined at column:" % name, self.lex.start
            self.lex.showerror()
开发者ID:inteljack,项目名称:EL6183-Digital-Signal-Processing-Lab-2015-Fall,代码行数:22,代码来源:parser1.py

示例3: __init__

# 需要导入模块: from scanner import Scanner [as 别名]
# 或者: from scanner.Scanner import newtext [as 别名]
class Parser:
    def __init__(self, text=''):
        self.lex  = Scanner(text)              # embed a scanner
        self.vars = {'pi': 3.14159}            # add a variable

    def parse(self, *text):
        if text:                               # main entry-point
            self.lex.newtext(text[0])          # reuse this parser?
        try:
            self.lex.scan()                    # get first token
            self.Goal()                        # parse a sentence
        except SyntaxError:
            print('Syntax Error at column:', self.lex.start)
            self.lex.showerror()
        except LexicalError:
            print('Lexical Error at column:', self.lex.start)
            self.lex.showerror()
        except UndefinedError as E:
            name = E.args[0]
            print("'%s' is undefined at column:" % name, self.lex.start)
            self.lex.showerror()

    def Goal(self):
        if self.lex.token in ['num', 'var', '(']:
            val = self.Expr()
            self.lex.match('\0')                    # expression?
            print(val)
        elif self.lex.token == 'set':               # set command?
            self.Assign()
            self.lex.match('\0')
        else:
            raise SyntaxError()

    def Assign(self):
        self.lex.match('set')
        var = self.lex.match('var')
        val = self.Expr()
        self.vars[var] = val           # assign name in dict

    def Expr(self):
        left = self.Factor()
        while True:
            if self.lex.token in ['\0', ')']:
                return left
            elif self.lex.token == '+':
                self.lex.scan()
                left = left + self.Factor()
            elif self.lex.token == '-':
                self.lex.scan()
                left = left - self.Factor()
            else:
                raise SyntaxError()

    def Factor(self):
        left = self.Term()
        while True:
            if self.lex.token in ['+', '-', '\0', ')']:
                return left
            elif self.lex.token == '*':
                self.lex.scan()
                left = left * self.Term()
            elif self.lex.token == '/':
                self.lex.scan()
                left = left / self.Term()
            else:
                raise SyntaxError()

    def Term(self):
        if self.lex.token == 'num':
            val = self.lex.match('num')               # numbers
            return val
        elif self.lex.token == 'var':
            if self.lex.value in self.vars.keys():    # keys(): EIBTI!
                val = self.vars[self.lex.value]       # look up name's value
                self.lex.scan()
                return val
            else:
                raise UndefinedError(self.lex.value)
        elif self.lex.token == '(':
            self.lex.scan()
            val = self.Expr()                         # sub-expression
            self.lex.match(')')
            return val
        else:
            raise SyntaxError()
开发者ID:KhalidEzzeldeen,项目名称:BitsAndBobs,代码行数:87,代码来源:parser1.py

示例4: __init__

# 需要导入模块: from scanner import Scanner [as 别名]
# 或者: from scanner.Scanner import newtext [as 别名]
class Parser:
    def __init__(self, text=""):
        self.lex = Scanner(text)  # make a scanner
        self.vars = {"pi": 3.14159}  # add constants
        self.traceme = TraceDefault

    def parse(self, *text):  # external interface
        if text:
            self.lex.newtext(text[0])  # reuse with new text
        tree = self.analyse()  # parse string
        if tree:
            if self.traceme:  # dump parse-tree?
                print()
                tree.trace(0)
            if self.errorCheck(tree):  # check names
                self.interpret(tree)  # evaluate tree

    def analyse(self):
        try:
            self.lex.scan()  # get first token
            return self.Goal()  # build a parse-tree
        except SyntaxError:
            print("Syntax Error at column:", self.lex.start)
            self.lex.showerror()
        except LexicalError:
            print("Lexical Error at column:", self.lex.start)
            self.lex.showerror()

    def errorCheck(self, tree):
        try:
            tree.validate(self.vars)  # error checker
            return "ok"
        except UndefinedError as instance:  # args is a tuple
            varinfo = instance.args
            print("'%s' is undefined at column: %d" % varinfo)
            self.lex.start = varinfo[1]
            self.lex.showerror()  # returns None

    def interpret(self, tree):
        result = tree.apply(self.vars)  # tree evals itself
        if result != None:  # ignore 'set' result
            print(result)  # ignores errors

    def Goal(self):
        if self.lex.token in ["num", "var", "("]:
            tree = self.Expr()
            self.lex.match("\0")
            return tree
        elif self.lex.token == "set":
            tree = self.Assign()
            self.lex.match("\0")
            return tree
        else:
            raise SyntaxError()

    def Assign(self):
        self.lex.match("set")
        vartree = VarNode(self.lex.value, self.lex.start)
        self.lex.match("var")
        valtree = self.Expr()
        return AssignNode(vartree, valtree)  # two subtrees

    def Expr(self):
        left = self.Factor()  # left subtree
        while True:
            if self.lex.token in ["\0", ")"]:
                return left
            elif self.lex.token == "+":
                self.lex.scan()
                left = PlusNode(left, self.Factor())  # add root-node
            elif self.lex.token == "-":
                self.lex.scan()
                left = MinusNode(left, self.Factor())  # grows up/right
            else:
                raise SyntaxError()

    def Factor(self):
        left = self.Term()
        while True:
            if self.lex.token in ["+", "-", "\0", ")"]:
                return left
            elif self.lex.token == "*":
                self.lex.scan()
                left = TimesNode(left, self.Term())
            elif self.lex.token == "/":
                self.lex.scan()
                left = DivideNode(left, self.Term())
            else:
                raise SyntaxError()

    def Term(self):
        if self.lex.token == "num":
            leaf = NumNode(self.lex.match("num"))
            return leaf
        elif self.lex.token == "var":
            leaf = VarNode(self.lex.value, self.lex.start)
            self.lex.scan()
            return leaf
        elif self.lex.token == "(":
            self.lex.scan()
#.........这里部分代码省略.........
开发者ID:shantanuo,项目名称:pp4p,代码行数:103,代码来源:parser2.py


注:本文中的scanner.Scanner.newtext方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。