gpt4 book ai didi

python - 如何在Python中的另一个字符串中找到列表中字符串的第一次出现

转载 作者:太空宇宙 更新时间:2023-11-03 19:05:15 27 4
gpt4 key购买 nike

我有一个字符串列表(大约 100 个),我想找到其中一个字符串在另一个字符串中第一次出现的情况以及它出现的索引。

我保留索引,并使用该索引中的另一个单词列表再次搜索后缀,然后返回第一个列表,直到到达字符串末尾。

我当前的代码(搜索第一次出现)如下所示:

        def findFirstOccurence(wordList, bigString, startIndex):
substrIndex = sys.maxint
for word in wordList:
tempIndex = bigString.find(word, startIndex)
if tempIndex < substrIndex and tempIndex != -1:
substrIndex = tempIndex
return substrIndex

这段代码完成了这项工作,但需要花费很多时间(我对相同的单词列表运行了几次,但在 100 个大字符串中(每个字符串大约 10K-20K 个单词)。

我确信有更好的方法(以及更Pythonic的方法)。

最佳答案

这看起来效果很好,并告诉您它找到了什么单词(尽管可以省略):

words = 'a big red dog car woman mountain are the ditch'.split()
sentence = 'her smooth lips reminded me of the front of a big red car lying in the ditch'

from sys import maxint
def find(word, sentence):
try:
return sentence.index(word), word
except ValueError:
return maxint, None
print min(find(word, sentence) for word in words)

关于python - 如何在Python中的另一个字符串中找到列表中字符串的第一次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14919171/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com