繁体   English   中英

在Python中查找字符串中所有事件的开始和结束位置

[英]Find start and end positions of all occurrences within a string in Python

如果有序列:

example='abcdefabcdefabcdefg'

和您的搜索:

searching_for='abc'

什么功能可以列出所有职位?

positions=[(0,2),(6-8),(12-14)]

我创建了一个窗口列表,该窗口列表将“ example”除以3,因此它取自“ abc”,“ bcd”,“ cde”

windows=['abc', 'bcd', 'cde', 'def', 'efa', 'fab', 'abc', 'bcd', 'cde', 'def', 'efa', 'fab', 'abc', 'bcd', 'cde', 'def']

并使用了for循环

for i in windows:
    if i == 'abc':

多数民众赞成在我卡住。

您可以使用正则表达式 匹配对象来与位置信息附加 使用Python 2的示例:

>>> import re
>>> example = 'abcdefabcdefabcdefg'
>>> for match in re.finditer('abc', example):
        print match.start(), match.end()
0 3
6 9 
12 15

re模块可提供您所需的内容。

import re
print [(m.start(0), m.end(0)) for m in re.finditer('abc', 'abcdefabcdefabcdefg')]

列表理解很好地表达了这一点:

positions = [(i, i + len(searching_for) - 1)
             for i in xrange(len(example))
             if example[i:].startswith(searching_for)]

请注意,它往往更多有用的结束索引点中最后一个字符 ,而不是最后一个字符,你问(和上面的代码提供)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM