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

标签 python

我试图获取字符串中键的所有索引并将它们存储在字典中,以便 每个索引都有一个映射到它的键列表。

示例:

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

关于如何做得更好有什么建议吗?

最佳答案

非正则表达式方法:

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

关于python - 将键(全部出现在给定字符串中)映射到字符串中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12554422/

相关文章:

python - 来自 django-admin 的 Flask-admin 查询集模拟

python - Django 导入错误 : cannot import name 'ReporterProfile' from partially initialized module 'accounts.models' (most likely due to a circular import)

矩阵的 Python Scipy spearman 相关性与双数组相关性不匹配,也不匹配 pandas.Data.Frame.corr()

python - xgboost 中的多类分类(python)

python - 如何知道 openpyxl 是否使用 defusedxml?

python - 将过程应用于多个子目录中的文件

python - psycopg2,我应该分块提交吗?

Python:如何制作标准大小为 6 的 struct.calcsize 整数?

python - 从 HTML 中提取数据

python - Qt - 格式化要在样式表中使用的 QColor?