python - 在 Python 中用索引拆分字符串

标签 python

我正在寻找将句子拆分成单词的 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/

相关文章:

python - 将值分配给嵌套字典错误

python - 对 2 个文本执行差异,仅使用文本中每一行的一部分

python - 在使用 NumPy 时理解 randn 的最小值和最大值

python - 在多个模块中使用函数类型的错误签名错误

python - 如何唤醒房间里最多的人?

python - 我如何使用 lxml objectify 访问 SOAP 响应中的元素值

python - Python中按字节长度分割字符串

java - 为什么我们需要安装一个工具包(JDK)才能开始Java编程

python - 如何在 python 中减去日期时间/时间戳

python - 在条件 : O(n) or O(n^2)? 中调用 max 的列表理解的 Big-O