我正在寻找将句子拆分成单词的 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 是否有任何库方法可供我使用。任何帮助我计算单词索引的方法都会很棒。
最佳答案
下面是一个使用正则表达式的方法:
>>> 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)]
关于python - 在 Python 中用索引拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13734451/