【问题标题】:Python substring from beginning and return index (have duplicate case) [closed]从开始和返回索引的Python子字符串(有重复的情况)[关闭]
【发布时间】:2021-04-02 01:51:18
【问题描述】:

我有一个长字符串和相应长字符串的子字符串列表。

示例 1:

字符串:

" This is paragraph one "

子字符串列表:["This", "is paragraph", "one"]

我需要返回对应子串的索引

结果:[[0,4], [5, 17], [18, 21]]

示例 2: (可能有更多的空白,并且可能有重复的子字符串)

字符串:

"
This is a book       a book.
"

列表: 子串列表:["This", "is a", "book", "a", "book"]

结果:[[0,4], [5, 9], [10, 14], [21,22], [23, 27]]

【问题讨论】:

  • 请通过intro tourhelp centerhow to ask a good question 了解本网站的运作方式并帮助您改进当前和未来的问题,从而帮助您获得更好的答案。 “告诉我如何解决这个编码问题?”与 Stack Overflow 无关。您必须诚实地尝试解决方案,然后就您的实施提出具体问题。 Stack Overflow 无意取代现有的教程和文档。

标签: python list algorithm indexing substring


【解决方案1】:

您可以使用生成器函数:

def get_matches(s, sub):
   inds = []
   for i in sub:
      if (k:=[j for j in range(len(s)) if s[j:].startswith(i) and (not inds or j > max(inds))]):
         yield [k[0], k[0]+len(i)]
         inds.append(k[0])
         
s = 'This is a book       a book.'
subs = ['This', 'is a', 'book', 'a', 'book']
print(list(get_matches(s, subs)))

输出:

[[0, 4], [5, 9], [10, 14], [21, 22], [23, 27]]

【讨论】:

  • 这行得通!谢谢!
【解决方案2】:

您可以尝试以下方法:

s = "This is a book       a book."
subs = ["This", "is a", "book", "a", "book"]

bounds = []
end = 0
for sub in subs:
    bounds.append((start := s[end:].find(sub) + end, end := start + len(sub)))
print(bounds)

它给出:

[(0, 4), (5, 9), (10, 14), (21, 22), (23, 27)]

为了娱乐,同样使用re

s = "This is a book       a book."
subs = ["This", "is a", "book", "a", "book"]

import re 
re.match(".*".join(f"({t})" for t in subs), s).regs[1:]

它给出:

((0, 4), (5, 9), (10, 14), (21, 22), (23, 27))

【讨论】:

  • 感谢您的回答,但是,这在“example2”中无法处理
  • 另外,请不要回答无效问题。 “不费吹灰之力”的帖子属于此类。
猜你喜欢
  • 2020-11-17
  • 2017-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-26
  • 2021-01-10
  • 2016-01-09
相关资源
最近更新 更多