我有两个字符串,ab,我可以使用a.index(b)在字符串a中查找字符串b的索引.

a = """
Hello! This is a string which I am using to present a quesion to stackoverflow because I ran into a problem.
How do I solve this?
If anyone knows how to do this, please help!
"""
b = "How do I solve this"

idx = a.index(b)

但当字符串b不完全是字符串a的一部分时,这就行不通了.例如,字符串b为:

b = "How fo I solve rhis"

我想要一种方法,当"不匹配"字符数最多为5时,我们可以在a中找到b的索引.

推荐答案

简单的方法是迭代可能的索引,并计算从该索引开始的子字符串ab之间的不匹配,如果不匹配的数量低于阈值,则返回索引:

def fuzzy_index(a, b, max_mismatches=5):
    
    n_overall = len(a)
    n_to_match = len(b)
    if n_overall < n_to_match:
        return None
    if n_to_match <= max_mismatches:
        return 0
    
    for i in range(n_overall - n_to_match + 1):
        if sum(c_a != c_b for c_a, c_b in zip(a[i : i + n_to_match], b)
                ) <= max_mismatches:
            return i

        
a = """
Hello! This is a string which I am using to present a quesion to stackoverflow because I ran into a problem.
How do I solve this?
If anyone knows how to do this, please help!
"""
b = "How fo I solve rhis"

print(fuzzy_index(a, b))  # -> 110

您可能还想使用模糊字符串匹配的包,例如fuzzywuzzy

Python-3.x相关问答推荐

我在创建Pandas DataFrame时感到困惑

PythonPandas -通过知道位置(Loc)而不是索引来删除行

动态范围内来自另外两列的列求和

按一列分组,如果日期列相同,则在数字列中填写缺少的值

PythonPandas READ_EXCEL空数据帧

根据第一个字典的值序列对第二个字典进行排序

Python-Django 设置 Pandas DataFrame 的多索引不会分组/合并最后一个索引

python3,将整数转换为字节:对于小整数使用 to_bytes() 有哪些替代方法?

无法理解此递归函数的分配和环境用法

Python pandas将单元格值移动到同一行中的另一个单元格

从 yahoo Finance python 一次下载多只股票

pip install mysqlclient 失败为 mysqlclient 运行 setup.py bdist_wheel ... 错误

TimescaleDB:是否可以从 Python 调用create_hypertable?

如何为 Python 中的线程设置异步事件循环?

在 sklearn.decomposition.PCA 中,为什么 components_ 是负数?

__new__ 方法给出错误 object.__new__() 只接受一个参数(要实例化的类型)

pip install dryscrape 失败并显示错误:[Errno 2] 没有这样的文件或目录:'src/webkit_server'?

用 numpy nan 查找列表的最大值

为现有项目创建virtualenv

有效地判断一个元素是否在列表中至少出现 n 次