首页 > 解决方案 > Python 从列表及其变体创建正则表达式

问题描述

我有一个拉丁月份的列表:

latinMonths = ['januarii', 'februarii','martii', 'aprilis', 'maii', 'junii', 'julii', 'augusti', 'septembris', 'octobris', 'novembris', 'decembris']

不幸的是,在我的文字中,我发现它们的变体拼写不同,例如:'januarij'或'septembrjs'等......

我正在尝试扫描文本以找到确切的单词作为列表或其变体。

我知道我可以使用 difflib 并发现我可以在这篇文章中检查一个带有单词列表的句子:Python: how to determine if a list of words exists in a string。有没有一种方法可以将两者结合起来,从而在字符串中找到一个实例,其中存在列表中的月份或其变体?

例如:如果我有文本“primo januarij 1487”,我想返回 true,因为 januarij 与 january 非常匹配,而如果我有“我爱西红柿”,则这两个词都与名单

标签: pythonlistdifflib

解决方案


使用fuzzywuzzy可以实现一个可能的解决方案,如下所示:

from fuzzywuzzy import fuzz

def fuzzy_months(text:str, months:list, treshold:float = 0.9)->bool:
    """Return if a word within the given text is close enough to any given month."""
    return max([fuzz.ratio(month,word) for month in latinMonths for word in test_string.split()])/100>= treshold

例如考虑以下短语test_string = 'lorem ipsum siptum abet septembrjs'fail_string = 'do you want to eat at McDonald?'

fuzzy_months(test_string, latinMonths)
>>> True

fuzzy_months(fail_string, latinMonths)
>>> False

推荐阅读