Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerate sentences in python

I have a tuple of strings that consists of two sentences

a = ('What', 'happened', 'then', '?', 'What', 'would', 'you', 'like', 'to', 'drink','?')

I tried this

for i,j in enumerate(a):
print i,j

which gives

0 What
1 happened
2 then
3 ?
4 What
5 would
6 you
7 like
8 to
9 drink
10 ?

whereas what I need is this

0 What
1 happened
2 then
3 ?
0 What
1 would
2 you
3 like
4 to
5 drink
6?
like image 914
user3635159 Avatar asked Jul 03 '15 06:07

user3635159


1 Answers

The simplest would be to manually increase i instead of relying on enumerate and reset the counter on the character ?, . or !.

i = 0
for word in sentence:
    print i, word

    if word in ('.', '?', '!'):
        i = 0
    else:
        i += 1
like image 86
jeromej Avatar answered Sep 23 '22 02:09

jeromej