映射键(全部出现在给定的字符串中)到字符串中的位置

时间:2012-09-23 17:15:11

标签: python

我试图获取字符串中键的所有索引并将它们存储在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

有关如何改善这一点的任何建议吗?

3 个答案:

答案 0 :(得分:1)

Non-regex方法:

使用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]}

答案 1 :(得分: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,而不是使用res.setdefault(match.start(), []).append(key),但它看起来并不漂亮。

答案 2 :(得分:0)

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