2015-04-21 70 views
1

我試圖找到一個文本文件「‘swp_pt’特定行的這一明確的子串行權,以取代一些在文本文件中,‘3’ '用雙引號和所有。我想將該號碼更改爲任何其他號碼,但我需要專門去第一個整數之後引用swp_pt變量並僅對其進行更改。我仍然試圖在文本文件中找到正確的swp_pt調用,並且還沒有做到這一點。嘗試使用正則表達式來找到在Python

這是到目前爲止我的代碼:

ddsFile = open('Product_FD_TD_SI_s8p.dds') 
for line in ddsFile: 
    print(line) 
    marker = re.search('("swp_pt", ")[0-9]+', line) 
print(marker) 
print(marker.group()) 
ddsFile.close() 

如果有人有線索如何做到這一點,我將非常感謝您的幫助。 Mike

回答

0

你真的需要在Python中做到這一點嗎? sed -i會做你想做的事情,並且相當簡單。

但是如果你需要的話,我會做這樣的事情:

def replace_swp_pt(line): 
    regex = r'"swp_pt", "(\d+)"' 
    replacement = '"swp_pt", "4"' 
    return re.sub(regex, replacement, line) 

def transform_file(file_name, transform_line_func): 
    with open(file_name, 'r') as f: 
    # Buffer full contents in memory. This only works if your file 
    # fits in memory; otherwise you will need to use a temporary file. 
    file_contents = f.read() 

    with open(file_name, 'w') as f: 
    for line in file_contents.split('\n'): 
     transformed_line = transform_line_func(line) 
     f.write(transformed_line + '\n') 

    if __name__ == '__main__': 
    transform_file('Product_FD_TD_SI_s8p.dds', replace_swp_pt)