2

I am trying to 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.

Example:

string = "loloo and foofoo at the foo bar"
keys = "foo", "loo", "bar", "lo"

i expect something like

{ 
  0: [lo]
  2: [loo, lo]
 10: [foo]
 13: [foo]
 24: [foo]
 28: [bar]
}

My current answer loos the following:

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

Any suggestions on how to make this better?

4

3 回答 3

1

Non-regex方法:

using str.find(),str.find()接受可选的第二个参数,它是您要查找单词的索引。

def indexes(word,strs):
    ind=0                #base index is 0
    res=[]
    while strs.find(word,ind)!=-1:   #loop until str.find() doesn't return -1
        ans=strs.find(word,ind)
        res.append(ans)
        ind=ans+1                 #change base index if the word is found
    return res     

strs = "loloo and foofoo at the foo bar"
keys = ["foo", "loo", "bar", "lo"]

print {x:indexes(x,strs) for x in keys}

输出:

{'lo': [0, 2], 'foo': [10, 13, 24], 'bar': [28], 'loo': [2]}
于 2012-09-23T17:29:15.233 回答
1

首先,re.escape如果它包含句点或类似的东西,您将需要密钥。除此之外,您可以采取更直接的方法来构建结果字典:

from collections import defaultdict
def get_index_for_string(string, keys):
    res = defaultdict(list)
    for key in keys:
        for match in re.finditer(re.escape(key), string):
            res[match.start()].append(key)
    return res

注意:除了使用defaultdict你还可以使用常规的 dict 和 do res.setdefault(match.start(), []).append(key),但它看起来不那么漂亮。

于 2012-09-23T19:22:36.270 回答
0

你在寻找什么样的“更好”?如果您需要更好的 Big-O 复杂性,请使用Aho-Corasic Automaton。有可用于 Python 的快速实现:

于 2012-09-23T18:59:07.987 回答