我在这里有一个功能:
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的情况下获取多个实例,以便索引保持不变?
答案 0 :(得分:0)
通过修改我的函数来找到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
答案 1 :(得分:0)
使用re
进行此操作import re
alldata='yse sadsa se se'
item='se'
resultedarray=[]
for matcheditem in re.finditer(item,alldata):
indexofs=matcheditem.start()
resultedarray.append(indexofs)