【问题标题】:Enumerate sentences in python在python中枚举句子
【发布时间】:2015-09-20 21:11:50
【问题描述】:

我有一个由两个句子组成的字符串元组

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?

【问题讨论】:

  • 我怎么知道元组中的第一行结束了?问号是分隔符吗?
  • 您的示例中有一个字符串元组。这与您在描述中所说的“一串两句话”不同
  • @Tanveer Alam:是的,没错,'?'是分隔符,但也可以是任何其他标点符号。

标签: python string enumerate


【解决方案1】:

最简单的方法是手动增加i 而不是依赖enumerate 并重置字符?.! 上的计数器。

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

    if word in ('.', '?', '!'):
        i = 0
    else:
        i += 1

【讨论】:

  • 这是一个不错且简单但非常有效的解决方案!我也喜欢其他建议,但我同意 @UlfR 的观点,即这是最不复杂的。
  • 知道这在shell 脚​​本或awk 中会是什么样子吗?
【解决方案2】:

可能过于复杂。我认为@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

【讨论】:

    【解决方案3】:

    还有一个:

    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 ?
    

    【讨论】:

      猜你喜欢
      • 2015-07-16
      • 2015-08-08
      • 2011-05-03
      • 1970-01-01
      • 2013-12-18
      • 1970-01-01
      • 2013-07-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多