【问题标题】:String split with indices in Python在 Python 中使用索引拆分字符串
【发布时间】:2012-12-05 23:32:58
【问题描述】:

我正在寻找pythonic方法将句子拆分为单词,并且还存储句子中所有单词的索引信息,例如

a = "This is a sentence"
b = a.split() # ["This", "is", "a", "sentence"]

现在,我还要存储所有单词的索引信息

c = a.splitWithIndices() #[(0,3), (5,6), (8,8), (10,17)]

实现 splitWithIndices() 的最佳方法是什么,python 是否有任何我可以使用的库方法。任何可以帮助我计算单词索引的方法都会很棒。

【问题讨论】:

  • a.index(x) 返回x 的索引。可以用。

标签: python


【解决方案1】:

这是一个使用正则表达式的方法:

>>> import re
>>> a = "This is a sentence"
>>> matches = [(m.group(0), (m.start(), m.end()-1)) for m in re.finditer(r'\S+', a)]
>>> matches
[('This', (0, 3)), ('is', (5, 6)), ('a', (8, 8)), ('sentence', (10, 17))]
>>> b, c = zip(*matches)
>>> b
('This', 'is', 'a', 'sentence')
>>> c
((0, 3), (5, 6), (8, 8), (10, 17))

作为单行:

b, c = zip(*[(m.group(0), (m.start(), m.end()-1)) for m in re.finditer(r'\S+', a)])

如果你只想要索引:

c = [(m.start(), m.end()-1) for m in re.finditer(r'\S+', a)]

【讨论】:

  • @f-j '*match' 在这里是什么意思?谢谢。
  • 这就是所谓的unpacking argument lists,或者splat运算符。基本上foo(*[a, b]) 将等同于foo(a, b)
【解决方案2】:

我认为返回相应拼接的开始和结束更自然。例如 (0, 4) 而不是 (0, 3)

>>> from itertools import groupby
>>> def splitWithIndices(s, c=' '):
...  p = 0
...  for k, g in groupby(s, lambda x:x==c):
...   q = p + sum(1 for i in g)
...   if not k:
...    yield p, q # or p, q-1 if you are really sure you want that
...   p = q
...
>>> a = "This is a sentence"
>>> list(splitWithIndices(a))
[(0, 4), (5, 7), (8, 9), (10, 18)]

>>> a[0:4]
'This'
>>> a[5:7]
'is'
>>> a[8:9]
'a'
>>> a[10:18]
'sentence'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 2014-01-20
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 2021-05-31
    相关资源
    最近更新 更多