2013-07-13 3 views
1

파이썬에서 읽고 싶은 파이썬 파일이 있는데 파이썬이 두 문자 사이의 문자열을 추출하기를 원합니다.파이썬에서 txt 파일의 문자 사이에 문자열을 추출하십시오.

일렬로

라인 B

라인 C

& TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTEST 예를 들면 다음과 같습니다!

라인 D

라인 전자 최대

내가 원하는 것은 라인을 읽을 수있는 파이썬이며이 발생하면 "&는"나는 ("$"로 선 포함) 라인 인쇄를 시작하려면 그것을 만날 때까지! "

제안 사항?

답변

3

이 작동 당신이 원하는 문자열이 쉽다 : 당신이 전체 파일을 읽을 수 있지만 사용하려는 경우,

with open('/tmp/test.txt','r') as f: 
    data=''.join(f.readlines())  

print data[data.index('&'):data.index('!')+1] 

또는 &!

import re 

with open('/tmp/test.txt','r') as f: 
    data=''.join(f.readlines())  

m=re.search(r'^(&.*!)\s*?\n',data,re.S | re.M)  
if m: print m.group(1) 
+0

실제로 작동합니다. 감사! – yamdoot

0

다음은 (매우 간단합니다!) 예입니다. 당신이 메모리에 모든 것을 읽는 것은 문제가되지 않는만큼 작은 파일 경우

data=[] 
flag=False 
with open('/tmp/test.txt','r') as f: 
    for line in f: 
     if line.startswith('&'): 
      flag=True 
     if flag: 
      data.append(line) 
     if line.strip().endswith('!'): 
      flag=False 

print ''.join(data) 

과의 시작과 끝으로 & 또는 !에는 모호함이 없다 :

def Printer(): 
    f = open("yourfile.txt") 
    Pr = False 
    for line in f.readlines(): 
     if Pr: print line 
     if "&" in line: 
      Pr = True 
      print line 
     if "!" in line: 
      Pr = False 
    f.close() 
0

하나의 간단한 해결책은 다음과 같습니다 : 그들이 각각 라인의 시작과 끝에서 f를, 당신은 정규식을 사용할 수 있습니다. 코드에는 각 코드 행을 이해할 수 있도록 많은 설명이 포함되어 있습니다. 뷰티 코드는 연산자를 사용하여 예외를 처리하고 리소스 (예 : 파일)를 닫습니다.

#Specify the absolute path to the input file. 
file_path = "input.txt" 

#Open the file in read mode. with operator is used to take care of try..except..finally block. 
with open(file_path, "r") as f: 
    '''Read the contents of file. Be careful here as this will read the entire file into memory. 
     If file is too large prefer iterating over file object 
    ''' 
    content = f.read() 
    size = len(content) 
    start =0 
    while start < size: 
     # Read the starting index of & after the last ! index. 
     start = content.find("&",start) 
     # If found, continue else go to end of contents (this is just to avoid writing if statements. 
     start = start if start != -1 else size 
     # Read the starting index of ! after the last $ index. 
     end = content.find("!", start) 
     # Again, if found, continue else go to end of contents (this is just to avoid writing if statements. 
     end = end if end != -1 else size 
     '''print the contents between $ and ! (excluding both these operators. 
      If no ! character is found, print till the end of file. 
     ''' 
     print content[start+1:end] 
     # Move forward our cursor after the position of ! character. 
     start = end + 1 
관련 문제