In [1]:
# Setup sample data
import random, string
def randomword():
return ''.join([random.choice(string.ascii_lowercase) for
_ in range(random.randrange(1, 8))])
sample = ' '.join([randomword() for _ in range(10000)]);
In [2]:
# Method one
def count(txt):
return len(txt.split())
%timeit count(sample)
In [3]:
# Method two
import re
def count2(txt):
return len(re.findall(r' ', txt))
%timeit count2(sample)
In [4]:
# Method three
def count3(txt):
count = 1
for i in txt:
if i == ' ':
count += 1
%timeit count3(sample)