[英]Enumerate sentences in python
我有一個由兩個句子組成的字符串元組
a = ('What', 'happened', 'then', '?', 'What', 'would', 'you', 'like', 'to', 'drink','?')
我試過這個
for i,j in enumerate(a):
print i,j
這使
0 What
1 happened
2 then
3 ?
4 What
5 would
6 you
7 like
8 to
9 drink
10 ?
而我需要的就是這個
0 What
1 happened
2 then
3 ?
0 What
1 would
2 you
3 like
4 to
5 drink
6?
最簡單的是手動增加i
而不是依賴enumerate
並重置字符上的計數器?
, .
或者!
。
i = 0
for word in sentence:
print i, word
if word in ('.', '?', '!'):
i = 0
else:
i += 1
可能過於復雜。 我認為@JeromeJ的解決方案更清晰。 但:
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
多一個:
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.