模糊启动

时间:2016-02-03 17:25:32

标签: python startswith

有没有办法执行模糊的“startswith”,这样如果第一个字符串以接近第二个字符串的内容开头,它将返回true?我的第一个想法是使用编辑距离阈值,但我不确定如何在startwith的上下文中这样做。

示例:

first_str = "My nam is Hello World"
second_str = "My name is"        
first_str.startswith(second_str) == True

1 个答案:

答案 0 :(得分:2)

fuzzywuzzy可以帮助排序

>>> from fuzzywuzzy import fuzz
>>> fuzz.partial_ratio("my name is joran","my nam is")

你需要pip install fuzzywuzzy然后你只需要选择一个“真实”的比例,这不一定意味着“它始于”我们可以用辅助函数做到这一点

def fuzzy_startswith(needle,haystack):
    n_words = len(needle.split())
    haystack_startswith = " ".join(haystack.split()[:n_words])
    return fuzz.ratio(needle,haystack_startswith)

fuzzy_startswith("my nam is","my name is joran")
相关问题