2012-10-25 5 views
2

큰 덩어리의 텍스트를 구문 분석하고 숫자를 얻기 위해 pyparsing을 사용했습니다. 내가 구문 분석하고 텍스트는이 같은 것입니다 : 나는 문자열을 검색하고 바로 주어진 문자열 후 다음 모든 값을 잡기 위해 필요한pyparsing 키워드는 어떻게 작동합니까?

asdkjh     1  120 203 
kajshd     230 2309 2309 
Activated Attempts  230 2309 2309 
Activated Attempts  230 2309 2309 
aksjdh        300 
... 

. 필자가 작성한 코드는 다음과 같습니다. 경우

returnValue= 0 

integer = pyparsing.Word(pyparsing.nums).setParseAction(lambda toks: int(toks[0])) 
attempted = integer.setResultsName("attempted") 
text = "Activated Attempts" 

row = text + attempted 
table = pyparsing.ZeroOrMore(pyparsing.Group(row) | pyparsing.SkipTo(row).suppress()) 

attempteds = [row.asDict() for row in table.parseString(self.sendLine("lts_pm p"))] 

for attempted in attempteds: 
    returnValue+= attempted["attempted"] 

return returnValue 

는 460 위의 기능을 반환 위는 주어진 "활성화 시도"저장 텍스트 뒤에 숫자를 검색, 숫자와 수익을 요약 한 것입니다.

그러나 나는 같은 스크립트에 더 많은 검색 쿼리를 추가 할 필요가, 나는 시도 :

text = pyparsing.Keyword("Activated Attempts") or pyparsing.Keyword("Non Attempts") 

그러나 스크립트는 "활성화 시도"잡아 그 수를 반환 완전히 두 번째 텍스트를 무시합니다. 그렇지 않은 경우 Keyword의 용도는 무엇입니까? 나는 또한 Literal을 시도했지만 그 중 하나도 성공하지 못했습니다!

답변

4
from pyparsing import * 

data = ''' 
asdkjh     1  120 203 
kajshd     230 2309 2309 
Activated Attempts  230 2309 2309 
Activated Attempts  230 2309 2309 
aksjdh        300 
''' 

eventParser = Group(Word(alphas) + Optional(Word(alphas))) 
rowParser = Group(eventParser + delimitedList(Word(nums),White(" "))) 
tableParser = ZeroOrMore(rowParser) 

def getValue(attemptsList, term): 
    value = 0 
    for attempt in attemptsList: 
     if ' '.join(attempt[0]) == term: 
      value += int(attempt[1]) 
    return value 

attempts = getValue(tableParser.parseString(data), "Activated Attempts") 
print attempts 

워드 프로세서 편집

에게

키워드 - 리터럴과 유사하지만, 즉시 공백, 구두점, 또는 다른 비 키워드 문자가 와야합니다; 정의 된 키워드로 시작하는 비 키워드의 우발적 인 일치를 방지합니다.

+0

답장을 보내 주셔서 감사합니다. 그러나 언급 된 "키워드"를 설명하거나 사용하지 않습니다. – theAlse

+0

@theAlse는 편집을 참조하십시오. – John

+0

문서를 인용하여 다시 +1 해 주시기 바랍니다. – PaulMcG