在 Python 的字符串中查找字符串列表中的项目索引

Find indexes of items in list of string in an string with Python

我正在寻找一种快速方法来查找字符串中与项目(一个或多个单词)匹配的所有索引。实际上我不需要列表中的索引我需要字符串中的索引。

我有一个单词列表和一个像这样的字符串:

words = ['must', 'shall', 'may','should','forbidden','car',...]
string= 'you should wash the car every day'

desired output:
[1,4]# should=1, car=4

有时列表的长度可以超过数百项,而字符串则可以达到数万。

我正在寻找一种如此快速的方法,因为它在每次迭代中被调用了一千次。

我知道如何用循环实现它并逐一检查所有项目,但它太慢了!

一个解决方案是 words set 而不是 list 然后做简单的列表理解:

words = {'must', 'shall', 'may','should','forbidden','car'}
string= 'you should wash the car every day'

out = [i for i, w in enumerate(string.split()) if w in words]

print(out)

打印:

[1, 4]

你可以使用字典 查找字典的时间复杂度为 O(1)

string = 'you should wash the car every day'

wordToIndex = {word: index for index, word in enumerate(string.split())}

words = ['must', 'shall', 'may','should','forbidden','car']

result = [wordToIndex[word] for word in words if word in wordToIndex]

# [1,4]

你需要 Aho Corasick 算法。

给定一组字符串和一段文本,它会在 O(len+ans) 中的给定文本中找到该集合中所有字符串的出现次数,其中 len 是文本的长度,ans 是答案的大小。

它使用自动机,可以根据您的需要进行修改。

使用列表理解,

print([string.split().index(i) for i in string.split() if i in words]) 
#[1,4]