[英]How do I find multiple occurences of a string in a string and return the index of its location in a space-separated list?
我在這里有一個功能:
def get_books(msg):
results = []
for key, value in books.items():
for item in value:
if item in msg:
last_item = item.split(" ")[-1]
msg_split = msg.split(" ")
if last_item in msg_split:
index = msg_split.index(last_item)
results.append((key, index))
return results
而且,我需要找到一種方法,使該功能可以檢測多張同名書籍。
例如, Exodus 1:1 blah blah blah John 1:2
返回[("exod", 0), ("john", 5)]
,但Exodus 1:1 blah blah blah Exodus 1:2
僅返回[("exod", 0)]
。
我將如何修改我的函數,以便在不修改msg_split的情況下選擇多個實例,使索引保持不變?
通過修改我的函數以查找枚舉的msg_split
所有索引來msg_split
:
def get_books(msg):
results = []
for key, value in books.items():
for item in value:
if item in msg:
last_item = item.split(" ")[-1]
msg_split = msg.split(" ")
indices = [i for i, x in enumerate(msg_split) if x == last_item]
for index in indices:
results.append((key, index))
return results
這是通過使用re來完成的
import re
alldata='yse sadsa se se'
item='se'
resultedarray=[]
for matcheditem in re.finditer(item,alldata):
indexofs=matcheditem.start()
resultedarray.append(indexofs)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.