2013-06-20 2 views
0

파일을 토큰 목록으로 구문 분석하려고합니다. 각 토큰은 최소한 하나의 행을 포함하지만 더 많은 행으로 구성 될 수 있습니다. 각 토큰은 정규식과 일치합니다. 입력이 일련의 토큰이 아닌 경우 (즉, 사이에 쓰레기가 나오지 않거나 뒤 따르는 경우) 오류를 신호하고 싶습니다. 나는 입력 파일이 비교적 작기 때문에 메모리 소비에 관심이 없다.파이썬으로 파일을 정규 표현식의 순서로 토큰 화하는 방법은 무엇입니까?

$s = slurp_file(); 
while ($s ne '') { 
    if ($s =~ s/^\nsection (\d)\n\n/p) { 
    push (@r, ['SECTION ' . $1, ${^MATCH}]); 
    } elsif ($s =~ s/^some line\n/p) { 
    push (@r, ['SOME LINE', ${^MATCH}]); 
    [...] 
    } else { 
    die ("Found garbage: " . Dumper ($s)); 
    } 
} 

나는 물론 포트의이 한 수 : 파이썬에 1 만이 할 수있는 더 파이썬 방법이

펄에서, 나는 (의사 코드) 같은 것을 사용하는 것이? (나는 하지이 라인별로 분석 한 후 상단에 손으로 만들어진 상태 시스템을 구축하고자 않습니다.)

답변

2

여기에 도움이 될 수있는 re 모듈에서 undocumented tool 있습니다. 이처럼 사용할 수 있습니다

import re 
import sys 

def section(scanner, token): 
    return "SECTION", scanner.match.group(1) 

def some_line(scanner, token): 
    return "SOME LINE", token 

def garbage(scanner, token): 
    sys.exit('Found garbage: {}'.format(token)) 

# scanner will attempt to match these patterns in the order listed. 
# If there is a match, the second argument is called. 
scanner = re.Scanner([ 
    (r"section (\d+)$$", section), 
    (r"some line$", some_line), 
    (r"\s+", None), # skip whitespace 
    (r".+", garbage), # if you get here it's garbage 
    ], flags=re.MULTILINE) 


tokens, remainder = scanner.scan('''\ 

section 1 

some line 
''') 
for token in tokens: 
    print(token) 

('SECTION', '1') 
('SOME LINE', 'some line') 
를 산출
관련 문제