2013-09-23 3 views
1

네트워크 인증을위한 실험실을 만들고 있습니다. 13 개의 장치에 대한 몇 가지 구성이 있지만 재료가 만들어진 것과 똑같은 장치가 없기 때문에 구성을 일부 변경해야합니다.Python : 여러 문자열을 파일의 여러 문자열로 바꿉니다.

나는 파이썬 스크립트를 만들려고했지만, 필자가 필요로하는 것과 정확하게 일치하지 않습니다.

나는 변경 파일이 형태로 만들 수 있습니다

발견-이는 이런 식으로 뭔가를 (보이는, 그래서 대체-와-이 내가 변경해야 지금 구성은 주로 intarfaces입니다 나는 일부 구성 톰를 제거한)가 작게 만들 : I 교체 할

interface Serial0 
description Connected to R1 
frame-relay route 102 interface Serial1 201 
frame-relay route 103 interface Serial2 301 
frame-relay route 104 interface Serial4 401 
frame-relay route 105 interface Serial5 501 
frame-relay route 113 interface Serial3 311 
! 
interface Serial1 
description Connected to R2 
frame-relay route 201 interface Serial0 102 
frame-relay route 203 interface Serial2 302 
frame-relay route 204 interface Serial4 402 
frame-relay route 205 interface Serial5 502 
frame-relay route 213 interface Serial3 312 
! 

또는 같은: 내가 원하는

interface Serial0/0 
! 
interface Serial0/0.1 point-to-point 
! 
interface Serial0/1 
! 

내가이 방법으로 라인으로 라인 그것을 지금

Serial0/0,Serial0/2/0 
Serial0/1,Serial0/1/0 

를 대체 :

def replace_all(text, dic): 
    for i, j in dic.iteritems(): 
     text = re.sub("\\b"+i+"\\b", j, text) 

내 문제가 있다는 것입니다 Serial0에 또는 Serial0/0가 처음으로 일치하고 Serial1/0으로 변경되었지만 Serial1에 의해 일치되므로 Serial1/1/0을 얻습니다. boundry (\ b)와^및 $를 모두 시도했지만 작동하지 않습니다. 또한 내가 그 사건은 Serial1 될 수 있지만 Serial1/0 아니지만 Serial1.200와 okey이야.

그래서 정확히 무엇을 찾고 싶습니까? 정확하게 원하는 것은 + 점과 일부 숫자를 찾습니다. Serial0/1.200

누구나이 방법을 알고 있고 올바른 방향으로 나를 가리킬 수 있습니까?

답변

0

당신은 루프 라인으로 라인을 처리하고 깰 수는 정규식에 일치를 원하는 경우 사용한다 분할

str_list = line.split(" ") 
if len(str_list) > 4: #case the line has interface 
    process(str_list[4]) 

def process(str_to_match): 
    if str_to_match in dic: 
      return dic[str_to_match] #will get the exact match saved in the dict 
    return str_to_match #not in dict dont replace 
0

비효율적이지만 효과적인 방법은 코드를 통해 for 루프와 같은 while 루프를 수동으로 수행하고 단어 목록에 대해 position 변수 앞에있는 문자열을 확인한 다음 적중이 있으면 교체하고 길이를 추가하는 것입니다 대체 단어를 위치 변수에 추가합니다. 추악하지만 쉽고 효과적입니다.

new_text="" 
for line in lines: 
    new_text= new_text + fix_line(line) 

def fix_line(line): 
    for i, j in dic.iteritems(): 
      new_line = re.sub("\\b"+i+"\\b", j, line) 
      if new_line != line: #line changed stop loop 
       return new_line 
    return line #line didn't match 

print(new_text) 

편집 :

관련 문제