2013-04-16 6 views
0

프리/포스트 앰블이 여러 번있는 메시지를 전송 중입니다. 나는 유효한 두 pre/postambles 사이에서 메시지를 추출 할 수 있기를 원한다. 내 curent 코드는 문제는 꼬리말이 손상된 경우, 그것은 첫 번째 유효한 프리앰블과 다음 유효한 꼬리말 사이의 모든 데이터를 인쇄하는 것입니다파이썬 next substring 검색

print(msgfile[msgfile.find(preamble) + len(preamble):msgfile.find(postamble, msgfile.find(preamble))]) 

입니다.

garbagePREAMBLEmessagePOSTcMBLEgarbage 
garbagePRdAMBLEmessagePOSTAMBLEgarbage 
garbagePREAMBLEmessagePOSTAMBLEgarbage 

하고 유효한 사전/사후을 모두 가지고 있기 때문에 그것은

messagePOSTcMBLEgarbage 
garbagePRdEAMBLEmessage 

는하지만 난 정말 그것을 인쇄 할 것은 세 번째 줄의 메시지입니다 인쇄됩니다 : 예받은 텍스트 파일 것 산보. 그래서 내가 원하는 것은 substring의 다음 인스턴스를 찾아 인덱스 할 수 있다는 것이다. 이 작업을 수행하는 쉬운 방법이 있습니까?

편집 : 내 데이터가 멋진 이산 라인에있을 것으로 기대하지 않습니다. 난 그냥보고 쉬울 것, 그래서 그런 식으로 형식

답변

0

과정이 라인으로 라인 :

>>> test = "garbagePREAMBLEmessagePOSTcMBLEgarbage\n" 
>>> test += "garbagePRdAMBLEmessagePOSTAMBLEgarbage\n" 
>>> test += "garbagePREAMBLEmessagePOSTAMBLEgarbage\n" 
>>> for line in test.splitlines(): 
     if line.find(preamble) != -1 and line.find(postamble) != -1: 
      print(line[line.find(preamble) + len(preamble):line.find(postamble)]) 
0
import re 

lines = ["garbagePREAMBLEmessagePOSTcMBLEgarbage", 
     "garbagePRdAMBLEmessagePOSTAMBLEgarbage", 
     "garbagePREAMBLEmessagePOSTAMBLEgarbage"] 

# you can use regex 
my_regex = re.compile("garbagePREAMBLE(.*?)POSTAMBLEgarbage") 

# get the match found between the preambles and print it 
for line in lines: 
    found = re.match(my_regex,line) 
    # if there is a match print it 
    if found: 
     print(found.group(1)) 

# you can use string slicing 
def validate(pre, post, message): 
    for line in lines: 
     # method would break on a string smaller than both preambles 
     if len(line) < len(pre) + len(post): 
      print("error line is too small") 

     # see if the message fits the pattern 
     if line[:len(pre)] == pre and line[-len(post):] == post: 
      # print message 
      print(line[len(pre):-len(post)]) 

validate("garbagePREAMBLE","POSTAMBLEgarbage", lines) 
0

가 하나의 라인에있는 모든 메시지인가? 은 그럼 당신은 유효한 사전 및 꼬리말에 선 식별하는 정규 표현식을 사용할 수 있습니다

input_file = open(yourfilename) 
import re 
pat = re.compile('PREAMBLE(.+)POSTAMBLE') 
messages = [pat.search(line).group(1) for line in input_file 
      if pat.search(line)] 

print messages 
+0

이 좋은 개별 라인 잘 작동을하지만 데이터가 전혀 포맷 할 것으로 예상니까. 방금보기 쉽게하기 위해 그렇게했습니다. – tdfoster

+0

메시지에 구조가 있습니까? 최대 길이, 제한된 문자 세트, 아무것도? –