【问题标题】:Text Pattern Recognition Python文本模式识别 Python
【发布时间】:2017-11-07 22:44:37
【问题描述】:

假设您有一组非常嘈杂的文本,并且您希望每次都选择一个定义的模式,例如\d{3}(?:\.||\s)\d{3}。问题是,这种模式可能出现在许多情况下,例如"443 440 $""923 140 €""923 140 EUR""product id 001 012""id prod. 001 012""product 001 012" 是否出现在相同的文本中。
正如我们所看到的,该模式匹配所有这些。 例如:

text1 = "Here it is simple because my text includes only one regexp matching which is 443 440 ID"
text2 = "But in some other texts, the regexp can be corresponding to a product profit 956.000 EUR for the product ID 001 023"
text3 = "Also, it can be found that the product 001.079 has a profit of 900 000 $USD"
text4 = "It can be analyzed that the 001789 product contains 001 000 components"

在这里我想确定我收集的是正确的东西:产品 ID [443 440, 001 023, 001.079, 001789]

你会怎么处理?

在现实世界中,可以发现一些特征可能有助于确定数字是否真的是产品ID(正则表达式在文本中的位置-一般在开头,常量判别词-EUR $, ...)

【问题讨论】:

    标签: python regex machine-learning


    【解决方案1】:

    你可以试试这个:

    import re 
    import itertools
    text1 = "Here it is simple because my text includes only one regexp matching which is 443 440 ID"
    text2 = "But in some other texts, the regexp can be corresponding to a product profit 956.000 EUR for the product ID 001 023"
    text3 = "Also, it can be found that the product 001.079 has a profit of 900 000 $USD"
    text4 = "It can be analyzed that the 001789 product contains 001 000 components"
    s = [text1, text2, text3, text4]
    final_ids = [re.findall('[\d\s\.]+(?=ID)|(?<=ID)\s*[\d\s\.]+|[\d\s\.]+(?=product)|(?<=product)\s*[\d\s\.]+', i) for i in s]
    new_final_ids = [[re.sub('^\s+|\s+$', '', b) for b in i if re.findall('\d+', b)][0] for i in final_ids]
    

    输出:

    ['443 440', '001 023', '001.079', '001789']
    

    【讨论】:

      【解决方案2】:

      您可以使用http://regex.inginf.units.it/ 根据示例数据生成正则表达式。如果你有足够大的训练集,它应该可以完成工作。

      对于您的四个示例,它生成了这个:001[^\d]\d++ 当然,它并不适用于所有情况,但通过更多示例,您可能会得到更好的结果。

      【讨论】:

        猜你喜欢
        • 2022-11-28
        • 2012-09-21
        • 1970-01-01
        • 2012-03-05
        • 2015-12-06
        • 2013-11-19
        • 1970-01-01
        • 1970-01-01
        • 2019-01-08
        相关资源
        最近更新 更多