Ok, so given the string:
s = "Born in Honolulu Hawaii Obama is a graduate of Columbia University and Harvard Law School"
I want to retrieve:
[ ["Born"], ["Honolulu", "Hawaii", "Obama"], ["Columbia", "University"] ...]
Assuming that we have successfully tokenised the original string, my first psuedocodish attempt was:
def retrieve(tokens):
results = []
i = 0
while i < len(tokens):
if tokens[i][0].isupper():
group = [tokens[i]]
j = i + 1
while i + j < len(tokens):
if tokens[i + j][0].isupper():
group.append(tokens[i + j])
j += 1
else:
break
i += 1
return results
This is actually quite fast (well compared to some of my trying-to-be-pythonic attempts):
Timeit: 0.0160551071167 (1000 cycles)
Playing around with it, the quickest I can get is:
def retrive(tokens):
results = []
group = []
for i in xrange(len(tokens)):
if tokens[i][0].isupper():
group.append(tokens[i])
else:
results.append(group)
group = []
results.append(group)
return filter(None, results)
Timeit 0.0116229057312
Are there any more concise, pythonic ways to go about this (with similar execution times)?
[['B'], ['H'], ['H'], ['O'], ['C'], ['U'], ['H'], ['L'], ['S']]when I run it verbatim. – Austin Marshall Nov 25 '12 at 23:12