2015-10-08 37 views
1

這裏更換兩個過子之間的串是我的問題:有在文件中十個不同的標誌,我需要更換不同flags.For例子之間的字符串,該文件的內容:通過使用python

content of the file 
... 
... 
... 
FIRSTSTART 
111.467, 0.0, 0.0, 
    0.0, 0.0, 0.000, 0.000, 1.0, 3, 
    0.0, 0.0, 0.960, 0.001, 1.0, 4, 
FIRSTEND 
SECONDSTART 
111.467, 0.0, 0.0, 
    0.0, 0.0, 0.000, 0.000, 1.0, 4, 
    0.0, 0.0, 0.960, 0.001, 0.5, 4, 
SECONDEND 
THIRDSTART 
2.765, 0.0, 0.0, 
    0.0, 0.0, 0.000, 0.000, 1.0, 2, 
    0.0, 0.0, 1.470, 0.003, 4.0, 3, 
THIRDEND 
FORTHSTART 
2.765, 0.0, 0.0, 
    0.0, 0.0, 0.000, 0.0000, 1.0, 1, 
    0.0, 0.0, 2.350, 0.0040, 6.0, 3, 
FORTHEND 
FIFTHSTART 
2.765, 0.0, 0.0, 
    0.0, 0.0, 0.000, 0.0000, 1.0, 3, 
    0.0, 0.0, 2.410, 0.0040, 6.0, 3, 
FIFTHEND 
SIXTHSTART 
2.765, 0.0, 0.0, 
    0.0, 0.0, 0.000, 0.0000, 1.0, 3, 
    0.0, 0.0, 3.330, 0.0100, 12.0, 3, 
SIXTHEND 
SEVENTHSTART 
2.765, 0.0, 0.0, 
    0.0, 0.0, 0.000, 0.0000,1.0, 3, 
    0.0, 0.0, 3.960, 0.0100, 12.0, 3, 
SEVENTHEND 
EIGTHSTART 
40.00, 0.0, 0.0, 
    0.0, 0.0, 0.000, 0.0000,1.0, 3, 
    0.0, 0.0, 2.890, 0.0190, 1.717, 3, 
EIGTHEND 
NINETHSTART 
2.765, 0.0, 0.0, 
    0.0, 0.0, 0.000, 0.0000, 1.0, 1, 
    0.0, 0.0, 3.64, 0.0030, 0.5, 2, 
NINETHEND 
TENTHSTART 
2.765, 0.0, 0.0, 
    0.0, 0.0, 0.000, 0.0000, 1.0, 1, 
    0.0, 0.0, 4.39, 0.018, 10.0, 3, 
TENTHEND 
... 
... 
... 
content of the file... 
... 

我需要更換每個「START」和「END」 flags.Result我想要的字符串是:

content of the file 
    ... 
    ... 
    ... 
    FIRSTSTART 
    1a 
    FIRSTEND 
    SECONDSTART 
    2b 
    SECONDEND 
    THIRDSTART 
    3c 
    THIRDEND 
    FORTHSTART 
    4d 
    FORTHEND 
    FIFTHSTART 
    5e 
    FIFTHEND 
    SIXTHSTART 
    6f 
    SIXTHEND 
    SEVENTHSTART 
    7g 
    SEVENTHEND 
    EIGTHSTART 
    8h 
    EIGTHEND 
    NINETHSTART 
    9i 
    NINETHEND 
    TENTHSTART 
    10j 
    TENTHEND 
    ... 
    ... 
    ... 
    content of the file... 
    ... 

所以,我怎樣才能處理此文件。

+0

是否國旗變化或數量是恆定的? – Kadir

+0

@Kadir這十個標誌是不變的。 – Elivis

+0

你可以使用regex ** sub **方法。 – Kadir

回答

1

,它可以像這樣在Python來實現:(data.txt中的內容文件)

import re 

with open ("data.txt", "r") as myfile: 
    data = myfile.read() 

dict = {"FIRSTSTART(.+)FIRSTEND": "FIRSTSTART\n1a\nFIRSTEND", "SECONDSTART(.+)SECONDEND": "SECONDSTART\n2b\nSECONDEND", 
     "THIRDSTART(.+)THIRDEND": "THIRDSTART\n3c\nTHIRDEND", "FORTHSTART(.+)FORTHEND": "FORTHSTART\n4d\nFORTHEND", 
     "FIFTHSTART(.+)FIFTHEND": "FIFTHSTART\n5e\nFIFTHEND", "SIXTHSTART(.+)SIXTHEND": "SIXTHSTART\n6f\nSIXTHEND", 
     "SEVENTHSTART(.+)SEVENTHEND": "SEVENTHSTART\n7g\nSEVENTHEND", "EIGTHSTART(.+)EIGTHEND": "EIGTHSTART\n8h\nEIGTHEND", 
     "NINETHSTART(.+)NINETHEND": "NINETHSTART\n9i\nNINETHEND", "TENTHSTART(.+)TENTHEND": "TENTHSTART\n10j\nTENTHEND" 
     } 

for key, value in dict.iteritems(): 
    re_comp = re.compile(key, re.DOTALL) 
    data = re_comp.sub(value, data) 

print data