繁体   English   中英

词法分析

[英]Lexical analysis

我正在用Python学习词法分析器。 我正在使用Ply库对某些字符串进行词法分析。 我已经为某些C ++语言语法实现了以下词法分析器。

但是,我面临一个奇怪的行为。 当我在其他函数定义的末尾定义COMMENT states function definitions时,代码可以正常工作。 如果我在其他定义之前定义COMMENT state functions ,则//输入字符串中的sectoin开始时就会出现错误。

这是什么原因?

import ply.lex as lex

tokens = (
        'DLANGLE',       # <<
        'DRANGLE',       # >>
        'EQUAL',        # =
        'STRING',       # "144"
        'WORD',         # 'Welcome' in "Welcome."
        'SEMICOLON',    # ;

)

t_ignore                = ' \t\v\r' # shortcut for whitespace


states = (
        ('cppcomment', 'exclusive'),   # <!--
)



def t_cppcomment(t): # definition here causes errors
    r'//'
    print 'MyCOm:',t.value

    t.lexer.begin('cppcomment');



def t_cppcomment_end(t):
    r'\n'
    t.lexer.begin('INITIAL');


def t_cppcomment_error(t):
    print "Error FOUND"
    t.lexer.skip(1)

def t_DLANGLE(t):

    r'<<'
    print 'MyLAN:',t.value
    return t

def t_DRANGLE(t):
    r'>>'
    return t

def t_SEMICOLON(t):

    r';'
    print 'MySemi:',t.value
    return t;

def t_EQUAL(t):
        r'='
        return t

def t_STRING(t):
        r'"[^"]*"'
        t.value = t.value[1:-1] # drop "surrounding quotes"
        print 'MyString:',t.value
        return t

def t_WORD(t):
        r'[^ <>\n]+'
        print 'MyWord:',t.value
        return t




webpage = "cout<<\"Hello World\"; // this comment"
htmllexer = lex.lex()
htmllexer.input(webpage)
while True:
        tok = htmllexer.token()
        if not tok: break
        print tok

问候

只是想通了。 正如我将注释状态定义为exclusive ,它不会使用inclusive状态模块(如果注释模块在顶部定义,否则出于某种原因会使用它)。 因此,您将再次为注释状态重新定义所有模块。 因此, ply提供了error()模块,用于跳过未定义特定模块的字符。

它的,因为你没有规则,接受thiscomment ,真的你不关于什么的评论,你可以easilly这样做护理

t_cppcomment_ANYTHING = '[^\r\n]'

低于您的t_ignore规则

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM