2012-03-27 2 views
0

특정 패턴과 일치하는 마지막 줄을 파이썬으로 찾고 싶습니다. 내가 뭘 하려는지 특정 항목 (line_end)을 포함하는 마지막 줄을 찾아, 몇 가지 새로운 라인으로 정보 블록을 삽입합니다. 지금까지 내가 가진 :Python은 검색에서 마지막으로 일치 한 후 텍스트를 삽입합니다.

text = open(path).read() 
match_found=False 
for line in text.splitlines(): 
    if line_pattern in line: 
     match_found=True 
if not match_found: 

(line_end='</PropertyGroup> '가 아니라도 좋은 검색 단어 정규식을 사용하는 방법을 잘) 는 누군가가되도록 넘어 가고 마지막 검색 항목을 찾을 수있는 방법에 대한 조언과 도움, 그리고 수 거기에 텍스트 블록을 삽입 할 수 있습니까? 감사합니다. 파일이 큰없는 경우

+3

사용. [이 질문에 대한 답변] (http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – Irfy

답변

2

당신은 정규 표현식으로 XML을 구문 분석하는 것 같다 re

import re 

text = open(path).read() 
match_found=False 
matches = re.finditer(line_pattern, text) 

m = None  # optional statement. just for clarification 
for m in matches: 
    match_found=True 
    pass  # just loop to the end 

if (match_found): 
    m.start() # equals the starting index of the last match 
    m.end() # equals the ending index of the last match 

    # now you can do your substring of text to add whatever 
    # you wanted to add. For example, 
    text[1:m.end()] + "hi there!" + text[(m.end()+1):] 
+0

이것은 매우 유용합니다! 고맙습니다. – Thalia

+0

@ user1217150 감사합니다.하지만 XML을 조작하는 경우 lrfy의 조언을 따르십시오. –

1

, 당신은 역순으로 읽을 수 :

for line in reversed(open("filename").readlines()): 
    if line.rstrip().endswith('</PropertyGroup>'): 
     do_something(line) 
관련 문제