【问题标题】:Python creating a regex from a list and its variationsPython 从列表及其变体创建正则表达式
【发布时间】:2019-01-04 13:30:42
【问题描述】:

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

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 与 january 非常匹配,而如果我有“我爱西红柿”,这两个词都不是非常匹配或完全匹配列表中的单词

【问题讨论】:

  • 我不太清楚您要做什么。能举个例子吗?
  • 我认为您可能希望从列表中的单词中匹配levenshtein distance of 1 中的所有单词。一种简单但可行的方法是将文本拆分为单词列表,并为每个单词计算到所有月份的距离。
  • 我在想这个,但不幸的是我的文本可能很长并且包含一个日期......检查文本中的所有单词可能效率很低......认为还有另一种方法: S
  • 不可能为未定义的单词变体生成正则表达式。如果您想要一个正则表达式,那么您需要明确列出您希望找到的所有变体。
  • 谢谢,也许我可以生成预期的变化! :)

标签: python list difflib


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-17
    • 2010-10-01
    • 2019-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-02
    相关资源
    最近更新 更多