python - 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 非常匹配,而如果我有“我爱西红柿”,则这两个词都与名单
解决方案
使用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
推荐阅读
- python - 从 django ORM 中检索具有相关字段的查询
- postgresql - 使用 apache-nifi 将两列加在一起
- amazon-web-services - 来自 CloudWatch 规则的 AWS SAM Lambda 函数触发器
- blender - 您如何使用颜色渐变连续随机更改光点的颜色?
- javascript - 如何插入 @Html.DisplayFor(m => m.EventDetailSection.ContactAccountTel)
- javascript - 我究竟做错了什么。我想显示没有时间戳的日期但添加 50 天
- maven - 如何在 maven repo 下获取所有 pom.xml
- c# - 将用户名和密码移动到 ASP.NET Core Identity
- python - chrome 驱动程序无头选项不适用于链接?
- react-native - 更改 TextInput onFocus 和 onBlur.React-Native 时的样式