Lexer for Parsing到一行

时间:2012-12-23 00:49:24

标签: python ply

如果我有一个关键字,一旦遇到关键字,我怎样才能获取它,只需抓住该行的其余部分并将其作为字符串返回?一旦遇到行尾,就返回该行的所有内容。

以下是我正在查看的专栏:

  description here is the rest of my text to collect

因此,当词法分析器遇到描述时,我希望“这是我要收集的其余文本”作为字符串返回

我定义了以下内容,但它似乎抛出了一个错误:

states = (
     ('bcdescription', 'exclusive'),
)

def t_bcdescription(t):
    r'description '
    t.lexer.code_start = t.lexer.lexpos
    t.lexer.level = 1
    t.lexer.begin('bcdescription')

def t_bcdescription_close(t):
    r'\n'
    t.value = t.lexer.lexdata[t.lexer.code_start:t.lexer.lexpos+1]
    t.type="BCDESCRIPTION"
    t.lexer.lineno += t.valiue.count('\n')
    t.lexer.begin('INITIAL')
    return t

这是返回错误的一部分:

  File "/Users/me/Coding/wm/wm_parser/ply/lex.py", line 393, in token
raise LexError("Illegal character '%s' at index %d" % (lexdata[lexpos],lexpos), lexdata[lexpos:])
ply.lex.LexError: Illegal character ' ' at index 40

最后,如果我想为多个令牌使用此功能,我该如何实现?

感谢您的时间

2 个答案:

答案 0 :(得分:0)

为什么你需要在没有进一步信息的情况下使用词法分析器/解析器,这是不明显的。

>>> x = 'description here is the rest of my text to collect'
>>> a, b = x.split(' ', 1)
>>> a
'description'
>>> b
'here is the rest of my text to collect'

答案 1 :(得分:0)

您的代码没有大问题,事实上,我只是复制您的代码并运行它,它运作良好

import ply.lex as lex 

states = ( 
     ('bcdescription', 'exclusive'),
)

tokens = ("BCDESCRIPTION",)

def t_bcdescription(t):
    r'\bdescription\b'
    t.lexer.code_start = t.lexer.lexpos
    t.lexer.level = 1 
    t.lexer.begin('bcdescription')

def t_bcdescription_close(t):
    r'\n'
    t.value = t.lexer.lexdata[t.lexer.code_start:t.lexer.lexpos+1]
    t.type="BCDESCRIPTION"
    t.lexer.lineno += t.value.count('\n')
    t.lexer.begin('INITIAL')
    return t

def t_bcdescription_content(t):
    r'[^\n]+'

lexer = lex.lex()
data = 'description here is the rest of my text to collect\n'
lexer.input(data)

while True:
    tok = lexer.token()
    if not tok: break      
    print tok 

结果是:

LexToken(BCDESCRIPTION,' here is the rest of my text to collect\n',1,50)

所以也许你可以查看代码的其他部分

如果我想要这个功能用于多个令牌,那么你可以简单地捕获单词,当这些令牌中出现一个单词时,开始通过上面的代码捕获剩余的内容。

相关问题