我对上述方法进行了比较,同时采用了使用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个循环)。
sum(map(str.isupper, string))不起作用的任何理由。 - njzk2