我尝试获取字符串中键的所有索引并将它们存储在dict中,以便 每个索引都有一个映射到它的键列表。你知道吗
示例:
string = "loloo and foofoo at the foo bar"
keys = "foo", "loo", "bar", "lo"
我想是这样的
{
0: [lo]
2: [loo, lo]
10: [foo]
13: [foo]
24: [foo]
28: [bar]
}
我目前的答案如下:
def get_index_for_string(string, keys):
"""
Get all indexes of the keys in the string and store them in a dict, so that
every index has a list of keys mapping to it.
"""
key_in_string = dict((key, [m.start() for m in re.finditer(key, string)])
for key in keys if key in string)
index_of_keys = {}
for key, values in key_in_string.items():
for value in values:
if not value in index_of_keys:
index_of_keys[value] = []
index_of_keys[value].append(key)
return index_of_keys
有什么好的建议吗?你知道吗
首先,您需要
re.escape
键,以防它包含句点或类似的内容。除此之外,您还可以采取更直接的方法来构建结果dict:注意:除了使用
defaultdict
之外,您还可以使用常规dict并执行res.setdefault(match.start(), []).append(key)
,但它看起来并不漂亮。你知道吗你在寻找什么样的“更好”?如果需要更好的Big-O复杂性,可以使用Aho-Corasic Automaton。Python提供了一些快速实现:
Non-regex
方法:使用
str.find()
,str.find()
接受可选的第二个参数,该参数是要在其后面查找单词的索引。你知道吗输出:
相关问题 更多 >
编程相关推荐