[英]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?
The simplest would be to manually increase i
instead of relying on enumerate
and reset the counter on the character ?
最简单的是手动增加i
而不是依赖enumerate
并重置字符上的计数器?
, .
, .
or !
或者!
. 。
i = 0
for word in sentence:
print i, word
if word in ('.', '?', '!'):
i = 0
else:
i += 1
Overly complicated maybe. 可能过于复杂。 The solution of @JeromeJ is cleaner I think. 我认为@JeromeJ的解决方案更清晰。 But: 但:
a=('What', 'happened', 'then', '?', 'What', 'would', 'you', 'like', 'to', 'drink','?')
start = 0
try: end = a.index('?', start)+1
except: end = 0
while a[start:end]:
for i,j in enumerate(a[start:end]):
print i,j
start = end
try: end = a.index('?', start)+1
except: end = 0
One more: 多一个:
from itertools import chain
for n,c in chain(enumerate(a[:a.index('?')+1]), enumerate(a[a.index('?')+1:])):
print "{} {}".format(n,i)
....:
0 What
1 happened
2 then
3 ?
0 What
1 would
2 you
3 like
4 to
5 drink
6 ?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.