[英]Text Pattern Recognition Python
考虑到您有一组非常嘈杂的文本,并且您想每次选择一个已定义的模式,例如\\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(文本中regexp的位置-通常在开头,以恒定的区分词-EUR $,... )
您可以尝试以下方法:
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']
您可以使用http://regex.inginf.units.it/根据示例数据生成正则表达式。 如果您有足够多的培训,它应该可以完成工作。
对于您的四个示例,它生成了以下示例: 001[^\\d]\\d++
当然,它不能在您的所有情况下都起作用,但是通过更多示例,您可能会得到更好的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.