21

私は文を単語に分割し、文内のすべての単語のインデックス情報を保存する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 には、そのために使用できるライブラリ メソッドがありますか。単語のインデックスを計算するのに役立つ方法はどれも素晴らしいでしょう。

4

2 に答える 2

28

正規表現を使用した方法は次のとおりです。

>>> 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)]
于 2012-12-05T23:42:16.253 に答える
10

対応するスプライスの開始と終了を返す方が自然だと思います。例: (0, 3) の代わりに (0, 4)

>>> 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'
于 2012-12-06T00:04:55.487 に答える