2014-09-13 3 views
1

좋아요, 다음 코드 조각이 있습니다.regex에서 대체 사전 찾기

out = out + re.sub('\{\{([A-z]+)\}\}', values[re.search('\{\{([A-z]+)\}\}',item).group().strip('{}')],item) + " " 

또는 더 분류 :

out = out + re.sub(
    '\{\{([A-z]+)\}\}', 
    values[ 
     re.search(
      '\{\{([A-z]+)\}\}', 
      item 
     ).group().strip('{}') 
    ], 
    item 
) + " " 

을 그래서, 기본적으로, 당신은 그것을 포함 된 문자열을 주면 {{참조}}, 그것은 그것의 인스턴스를 발견하고 그들을 대체합니다 주어진 참조. 현재 형태의 문제는 첫 번째 참조를 기반으로 만 작동한다는 것입니다. 예를 들어, 제 값을 사전

values = { 
    'bob': 'steve', 
    'foo': 'bar' 
} 

이었다 말하고 우리는 그것을 문자열

item = 'this is a test string for {{bob}}, made using {{foo}}' 

나는 그것이 out

'this is a test string for steve, made using bar' 

에 넣어하지만은 현재 출력하는

입니다하려는 전달
'this is a test string for steve, made using steve' 

루프의 위치를 ​​고려하여 코드를 어떻게 변경합니까?

코드가 입력이 나는 다음과 같은 코드를 사용하여 출력을 가지고 {{foo}}{{steve}}

+2

가'[아즈]가'뿐만 아니라 APHA 것을주의, 그것은 Z'와'A''사이의 모든 문자가 포함 , 즉. '[\]^_'및 \' – Toto

+0

괜찮습니다. 코드 만 사용하고 있으며 그 기호를 사용하지는 않습니다. 어쨌든'[A-Za-z]'로 바꿀 수도 있습니다. –

+1

참조'{{reference}} '의 다른 형식을 사용할 수 있습니까? 왜냐하면 당신이 {reference}로 바꿀 수 있다면 그냥 다음과 같이하면됩니다 :''{bob}의 테스트 문자열입니다. {foo} '형식 (** values)' – miszczu

답변

0

경우에도 작업을 필요로 단어 분할을하는 것은, 작동하지 않을 것을 주목해야한다

replace_dict = { 'bob': 'steve','foo': 'bar'} 
item = 'this is a test string for {{foo}}, made using {{steve}}' 
replace_lst = re.findall('\{\{([A-z]+)\}\}', item) 
out = '' 
for r in replace_lst: 
    if r in replace_dict: 
     item = item.replace('{{' + r + '}}', replace_dict[r]) 
print item 
+0

끈의 어느 쪽이든, 나는 그것들을 벗겨 내고 싶다. 이거 추가 할 수 있니? –

+0

알아 냈어 :'item = item.replace ("{{"+ r + "}}", values ​​[r])' –

0

이건 어떻습니까? 당신이 {{reference}}에서 {reference} 참조의 형식을 변경할 수 있다면

import re 

values = { 
    'bob': 'steve', 
    'foo': 'bar' 
} 

item = 'this is a test string for {{bob}}, made using {{foo}}' 

pat = re.compile(r'\{\{(.*?)\}\}') 

fields = pat.split(item) 
fields[1] = values[fields[1]] 
fields[3] = values[fields[3]] 
print ''.join(fields) 
0

, 그냥 (대신 정규식을 사용하는) 형식의 방법으로 요구 사항을 달성 할 수 : 코드에서

values = { 
'bob': 'steve', 
'foo': 'bar' 
} 
item = 'this is a test string for {bob}, made using {foo}' 
print(item.format(**values)) 
# prints: this is a test string for steve, made using bar 
0

, re.search가 시작됩니다 당신이 그것을 부를 때마다 문자열의 처음부터보고, 따라서 항상 첫 번째 일치를 반환 {{bob}}.

당신은 passing a function as replacement to re.sub에 의해 현재 교체 경기 개체에 액세스 할 수 있습니다

values = { 'bob': 'steve','foo': 'bar'} 
item = 'this is a test string for {{bob}}, made using {{foo}}' 
pattern = r'{{([A-Za-z]+)}}' 
# replacement function 
def get_value(match): 
    return values[match.group(1)] 
result = re.sub(pattern, get_value, item) 
# print result => 'this is a test string for steve, made using bar'