더 빠른 작업, re.match / search 또는 str.find는 무엇입니까?
일회성 문자열 검색의 경우 re.match / search를 사용하는 것보다 단순히 str.find / rfind를 사용하는 것이 더 빠릅니까?
즉, 주어진 문자열 s에 대해 다음을 사용해야합니다.
if s.find('lookforme') > -1:
do something
또는
if re.match('lookforme',s):
do something else
?
질문 : 더 빠른 것은 timeit
.
from timeit import timeit
import re
def find(string, text):
if string.find(text) > -1:
pass
def re_find(string, text):
if re.match(text, string):
pass
def best_find(string, text):
if text in string:
pass
print timeit("find(string, text)", "from __main__ import find; string='lookforme'; text='look'")
print timeit("re_find(string, text)", "from __main__ import re_find; string='lookforme'; text='look'")
print timeit("best_find(string, text)", "from __main__ import best_find; string='lookforme'; text='look'")
출력은 다음과 같습니다.
0.441393852234
2.12302494049
0.251421928406
따라서 in
읽기 쉽기 때문에 연산자를 사용해야 할 뿐만 아니라 더 빠르기 때문입니다.
이것을 사용하십시오 :
if 'lookforme' in s:
do something
Regex를 먼저 컴파일해야하므로 오버 헤드가 추가됩니다. 파이썬의 일반적인 문자열 검색은 어쨌든 매우 효율적입니다.
같은 용어를 많이 검색하거나 더 복잡한 작업을 수행하면 정규식이 더 유용 해집니다.
re.compile은 같은 것을 반복해서 검색하는 경우 정규식 속도를 크게 향상시킵니다. 하지만 일치하기 전에 "in"을 사용하여 불량 사례를 제거함으로써 엄청난 속도 향상을 얻었습니다. 일화, 알아. ~ 벤
나는 같은 문제가 있었다. Jupyter의 % timeit을 사용하여 확인했습니다.
import re
sent = "a sentence for measuring a find function"
sent_list = sent.split()
print("x in sentence")
%timeit "function" in sent
print("x in token list")
%timeit "function" in sent_list
print("regex search")
%timeit bool(re.match(".*function.*", sent))
print("compiled regex search")
regex = re.compile(".*function.*")
%timeit bool(regex.match(sent))
x 문장에서 61.3ns ± 3ns 루프 당 (평균 ± 표준 dev. 7 회 실행, 각 10000000 루프)
x 토큰 목록에서 루프 당 93.3 ns ± 1.26 ns (평균 ± 표준 dev. 7 회 실행, 각 10000000 루프)
정규식 검색 루프 당 772ns ± 8.42ns (평균 ± 표준 dev. 7 회 실행, 각 1000000 루프)
컴파일 된 정규식 검색 루프 당 420ns ± 7.68ns (평균 ± 표준 dev. 7 회 실행, 각 1000000 회 루프)
컴파일은 빠르지 만 간단한 것이 좋습니다.
참고 URL : https://stackoverflow.com/questions/4901523/whats-a-faster-operation-re-match-search-or-str-find
'Nice programing' 카테고리의 다른 글
string 형 벡터를 할당하여 열 이름으로 빈 데이터 프레임을 만드시겠습니까? (0) | 2020.12.06 |
---|---|
.NET 소스 코드 디버깅을위한 .cs 파일을 찾을 수 없습니다. (0) | 2020.12.06 |
SqlException catch 및 처리 (0) | 2020.12.06 |
Regex를 사용하여 문자열에서 와일드 카드 (* ,? 등) 검색을 수행해야합니다. (0) | 2020.12.06 |
android : configChanges =“orientation”은 조각에서 작동하지 않습니다. (0) | 2020.12.06 |