Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xcode/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何创建用于识别CRs的ply规则?_Python_Lexer_Ply - Fatal编程技术网

Python 如何创建用于识别CRs的ply规则?

Python 如何创建用于识别CRs的ply规则?,python,lexer,ply,Python,Lexer,Ply,在我的PLY lexer中,我无法区分\r(0x0d)和\n(0x0a) 下面的程序是一个简单的例子 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

在我的PLY lexer中,我无法区分\r(0x0d)和\n(0x0a)

下面的程序是一个简单的例子

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,您可以在默认模式下打开该文件。在该模式下,
newline=None
,这意味着(除其他外)
\r
\n
\r\n
中的任何一个都被视为行尾,并转换为单个
\n
字符。有关详细信息,请参阅

您可以通过将
换行符=''
传递到
打开
来禁用此行为,这意味着它将接受任何类型的换行符,但不会将它们规范化为
\n

谢谢!(回想起来,我不知道为什么我从来没有想到这种行为可能与PLY以外的东西有关)。