我已经对上述方法 + RE 编译使用进行了一些比较
Python 3.7.4
为此,我使用了古腾堡项目的 Lewis Carroll 所著的《爱丽丝梦游仙境》一书。
from urllib.request import urlopen
# Download
text = urlopen('https://www.gutenberg.org/files/11/11-0.txt').read().decode('utf-8')
# Split it into the separate chapters and remove table of contents, etc
sep = 'CHAPTER'
chaps = [sep + ch for ch in text.split('CHAPTER') if len(ch) > 1000]
len(chaps)
将所有方法定义为函数,以便在循环中使用它们并保持简洁。
import re
import string
def py_isupper(text):
return sum(1 for c in text if c.isupper())
def py_str_uppercase(text):
return sum(1 for c in text if c in string.ascii_uppercase)
def py_filter_lambda(text):
return len(list(filter(lambda x: x in string.ascii_uppercase, text)))
def regex(text):
return len(re.findall(r'[A-Z]',text))
# remove compile from the loop
REGEX = re.compile(r'[A-Z]')
def regex_compiled(text):
return len(REGEX.findall(text))
结果如下。
%%timeit
cnt = [py_isupper(ch) for ch in chaps]
每个循环 7.84 毫秒 ± 69.7 微秒(平均值 ± 标准偏差。7 次运行,每次 100 次循环)
%%timeit
cnt = [py_str_uppercase(ch) for ch in chaps]
每个循环 11.9 毫秒 ± 94.6 微秒(平均值 ± 标准偏差。7 次运行,每次 100 次循环)
%%timeit
cnt = [py_filter_lambda(ch) for ch in chaps]
每个循环 19.1 毫秒 ± 499 微秒(平均值 ± 标准偏差。7 次运行,每次 100 次循环)
%%timeit
cnt = [regex(ch) for ch in chaps]
每个循环 1.49 毫秒 ± 13 微秒(平均值 ± 标准偏差。7 次运行,每次 1000 次循环)
%%timeit
cnt = [regex_compiled(ch) for ch in chaps]
每个循环 1.45 毫秒 ± 8.69 微秒(平均值 ± 标准偏差。7 次运行,每次 1000 次循环)