결정

2014-12-08 2 views
1

생각 운동 : 정규식 패턴 또는 정확하게 일치하는 문자열을 취하는 파이썬 함수를 작성하는 "최고"방법은 무엇입니까 :결정

import re 
strings = [...] 

def do_search(matcher): 
    """ 
    Returns strings matching matcher, which can be either a string 
    (for exact match) or a compiled regular expression object 
    (for more complex matches). 
    """ 
    if not is_a_regex_pattern(matcher): 
    matcher = re.compile('%s$' % re.escape(matcher)) 

    for s in strings: 
    if matcher.match(s): 
     yield s 

을 따라서는, 아이디어 is_a_regex_pattern() 구현을 위해?

답변

2

당신은 re._pattern_type를 통해 _sre.SRE_Pattern 유형에 액세스 할 수 있습니다

>>> import re 
>>> re._pattern_type 
<class '_sre.SRE_Pattern'> 
>>> isinstance(re.compile('abc'), re._pattern_type) 
True 
>>> 
0
  1. 문자열이 아닙니다

    def is_a_regex_pattern(s): 
        return s.__class__.__name__ == 'SRE_Pattern' 
    
  2. 당신은 다시 컴파일 할 수 있습니다 (즉 가져올 수 없습니다, 그래서 심한 문자열 일치를 사용하지만)

    def is_a_regex_pattern(s): 
        return not isinstance(s, basestring) 
    
  3. _sre.SRE_Pattern인가 SRE_Pattern 및 은 동일한 것으로 평가하려면 것으로 보입니다.

    import re 
    
    def do_search(matcher, strings): 
        """ 
        Returns strings matching matcher, which can be either a string 
        (for exact match) or a compiled regular expression object 
        (for more complex matches). 
        """ 
        if hasattr(matcher, 'match'): 
         test = matcher.match 
        else: 
         test = lambda s: matcher==s 
    
        for s in strings: 
         if test(s): 
          yield s 
    

    당신은 전역 변수를 사용하지만, 두 번째 매개 변수를 사용하지 않아야합니다 : matcher이 방법 match이있는 경우

    def is_a_regex_pattern(s): 
        return s == re.compile(s) 
    
0

또는,이 quack합니다 : 즉

try: 
    does_match = matcher.match(s) 
except AttributeError: 
    does_match = re.match(matcher.s) 

if does_match: 
    yield s 

, 치료 아래

if not isinstance(matcher, re._pattern_type): 
    matcher = re.compile('%s$' % re.escape(matcher)) 

는 데모입니다 matcher 이미 마치 a 컴파일 된 정규 표현식. 그리고 그게 깨진다면 문자열처럼 처리해야합니다.

Duck Typing입니다. 모두가 agrees이 아닌 경우 일상적인 우발 사건에 대해 예외를 사용해야합니다. 이것은 ask-permission versus ask-forgiveness 토론입니다. Python은 대부분의 언어보다 용서가 더 많습니다. amenable.