2013-04-29 4 views
3

내가 여기서 잘못하고있는 것이 궁금합니다. 어쩌면 누군가가 나에게이 문제에 대한 힌트를 줄 수 있습니다. _Init 문자열로 끝나는 pyparsing을 사용하여 특정 토큰을 검색하려고합니다. 예를 들어 번식 : 특정 끝자리가있는 토큰을 검색하십시오.

이, 나는 다음과 같은 라인이 나는 다음과 같은 라인을 추출 할 text

one 
two_Init 
threeInit 
four_foo_Init 
five_foo_bar_Init 

에 저장된 : 현재

two_Init 
four_foo_Init 
five_foo_bar_Init 

을, 나는 다음과 같은 라인에 내 문제를 감소 :

import pyparsing as pp 

    ident = pp.Word(pp.alphas, pp.alphanums + "_") 
    ident_init = pp.Combine(ident + pp.Literal("_Init")) 

    for detected, s, e in ident_init.scanString(text): 
     print detected 

이 코드를 사용하면 결과가 없습니다. Word 문에서 "_"을 제거하면 적어도 _Init의 행을 감지 할 수 있습니다. 그러나 결과는 완전하지 않습니다.

['two_Init'] 
['foo_Init'] 
['bar_Init'] 

내가 완전히 잘못하고있는 사람이 있습니까?

답변

2

문제는 '_'이 (가) '_Init'인데 '_'이 아닌 한 받아 들여야한다는 것입니다. 다음은 두 가지 pyparsing 솔루션입니다. 하나는 더 "순수한"pyparsing이고, 다른 하나는 방금 그것을 말하고 내장 된 정규식을 사용합니다.

samples = """\ 
one 
two_Init 
threeInit 
four_foo_Init 
six_seven_Init_eight_Init 
five_foo_bar_Init""" 


from pyparsing import Combine, OneOrMore, Word, alphas, alphanums, Literal, WordEnd, Regex 

# implement explicit lookahead: allow '_' as part of your Combined OneOrMore, 
# as long as it is not followed by "Init" and the end of the word 
option1 = Combine(OneOrMore(Word(alphas,alphanums) | 
          '_' + ~(Literal("Init")+WordEnd())) 
        + "_Init") 

# sometimes regular expressions and their implicit lookahead/backtracking do 
# make things easier 
option2 = Regex(r'\b[a-zA-Z_][a-zA-Z0-9_]*_Init\b') 

for expr in (option1, option2): 
    print '\n'.join(t[0] for t in expr.searchString(samples)) 
    print 

두 옵션 인쇄 :

two_Init 
four_foo_Init 
six_seven_Init_eight_Init 
five_foo_bar_Init 
관련 문제