3
我在我的PLY詞法分析器中區分\ r(0x0d)和\ n(0x0a)時遇到了麻煩。如何創建用於識別CR的層規則?
一個最小的例子是下面的程序
import ply.lex as lex
# token names
tokens = ('CR', 'LF')
# token regexes
t_CR = r'\r'
t_LF = r'\n'
# chars to ignore
t_ignore = 'abc \t'
# Build the lexer
lexer = lex.lex()
# lex
f = open('foo', 'r')
lexer.input(f.read())
while True:
tok = lexer.token()
if not tok: break
print(tok)
現在創建一個文件foo如下:
printf "a\r\n\r\rbc\r\n\n\r" > foo
驗證,它看起來不錯:
hd foo
00000000 61 0d 0a 0d 0d 62 63 0d 0a 0a 0d |a....bc....|
0000000b
現在我曾以爲我會得到一些CR和一些LF令牌,但是:
python3 crlf.py
WARNING: No t_error rule is defined
LexToken(LF,'\n',1,1)
LexToken(LF,'\n',1,2)
LexToken(LF,'\n',1,3)
LexToken(LF,'\n',1,6)
LexToken(LF,'\n',1,7)
LexToken(LF,'\n',1,8)
原來我只拿到LF令牌。我想知道爲什麼發生這種情況,而我應該怎麼做。
這是在Ubuntu 12.04上的Python 3.2.3
謝謝! (回想起來,我不知道爲什麼我從未想到這種行爲可能與PLY以外的事情有關)。 – esg