Python从列表创建正则表达式及其变体

2024-09-28 01:30:06 发布

您现在位置: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 exist in a string。有没有一种方法可以将两者结合起来,从而在一个字符串中找到一个实例,其中存在列表中的月份或其变体?你知道吗

例如:如果我有文本“primo januarij 1487”,我想返回true,因为januarij与一月非常接近,而如果我有“I love tomatoes”,则两个词都与列表中的词不完全匹配


Tags: 文本列表变体单词月份martiimaiilatinmonths
1条回答
网友
1楼 · 发布于 2024-09-28 01:30:06

可以使用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

相关问题 更多 >

    热门问题