查找字符串中下一次出现的位置

Find the position of the next occurrences in string

我是 python 的新手,正在尝试熟悉正则表达式和字符串处理。我写了一个正则表达式,通过它可以识别整个字符串中的数字并将其提取到数组中。

我想要一个包含找到的术语位置的并行数组。

为了澄清,假设主字符串是:

text = '11 scholars are selected to comptete on Feb 20 , 2019. 
Afterwards, 11 professors will review their submitted work. 
The results will be announced on Mar 20 , 2019.'

正如我所说,我可以从上面的字符串中匹配 nums = ['11', '20', '2019', '11', '20', '2019']。现在,我想形成一个同步数组来存储每个数字的位置。我正在使用以下代码段:

positions = []
for num in nums:
   pos = text.find(num)
   positions.append(num + ' : ' + str(pos))

positions 数组包含:positions = ['11 : 0', '20 : 44', '2019 : 49', '11 : 0', '20 : 44', '2019 : 49'] 这显然不是我想要的。由于列表中有重复的数字(如两个 11 或 12),因此 text.find(num) returns 首次出现该术语。因此,当程序到达标记的下一个出现位置时,它位于第一次出现的 returns 位置。

关于如何解决这个问题有什么想法吗?

你可以使用finditer which returns 迭代器产生匹配对象,你可以从这些匹配中得到匹配的字符串和起始位置:

import re

text = """11 scholars are selected to comptete on Feb 20 , 2019. 
Afterwards, 11 professors will review their submitted work. 
The results will be announced on Mar 20 , 2019."""

[(m.group(0), m.start()) for m in re.finditer(r'\d+', text)]
# [('11', 0), ('20', 44), ('2019', 49), ('11', 68), ('20', 154), ('2019', 159)]

或者,如果您希望将其格式化为您的问题:

['{}: {}'.format(m.group(0), m.start()) for m in re.finditer(r'\d+', text)]
# ['11: 0', '20: 44', '2019: 49', '11: 68', '20: 154', '2019: 159']

@Thierry 的方法肯定是 pythonic 并且很好地利用了正则表达式。更简单的做法如下:

positions = []
i=0
for num in nums:
   pos = text.find(num, i)
   positions.append(num + ' : ' + str(pos))
   i =+ pos + len(num)

print(positions)
['11 : 0', '20 : 44', '2019 : 49', '11 : 68', '20 : 153', '2019 : 158']