过滤产品模型的正则表达式(Python)

2024-09-19 23:28:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从惠普产品描述中过滤掉产品线和产品型号的信息

示例:

HP EliteDesk 800 G1 SFF (H3S08US#ABA)
HP Pro 3400 Series MT (H3S08US#ABA)
HP EliteBook 8460p (H3S08US#ABA)

预期产量:

Production line: EliteDesk
Production model: 800 G1

Production line: Pro
Production model: 3400 Series

Production line: EliteBook 
Production model: 8460p

这是我现在所拥有的

product_line = re.search('([a-zA-Z]+) ([a-zA-Z]*\d+[a-zA-Z]*)', model).group(1)
product_model = re.search('([a-zA-Z]+) ([a-zA-Z]*\d+[a-zA-Z]*)', model).group(2)

但是,在第一个和第二个示例中,输出结果为8003400

有没有更好的方法过滤掉这些信息?非常感谢你们的到来


Tags: 信息示例modellineproductprohpproduction
1条回答
网友
1楼 · 发布于 2024-09-19 23:28:28

使用regex和split

你可以使用:

"HP (\w+) (.*?) \((.*)\)"

这里是Regex101.com上的example

import re

text="""HP EliteDesk 800 G1 SFF (H3S08US#ABA)
HP Pro 3400 Series MT (H3S08US#ABA)
HP EliteBook 8460p (H3S08US#ABA)"""

pattern = re.compile("HP (\w+) (.*?) \((.*)\)")


for line, model, serial in re.findall(pattern, text):
    print "Production line : %s" % line
    print "Production model : %s" % ' '.join(model.split(' ')[:2]) # Only the first two words
    print "Serial number : %s" % serial
    print

它输出:

Production line : EliteDesk
Production model : 800 G1
Serial number : H3S08US#ABA

Production line : Pro
Production model : 3400 Series
Serial number : H3S08US#ABA

Production line : EliteBook
Production model : 8460p
Serial number : H3S08US#ABA

就用正则表达式

如果只需要regexp解决方案,可以使用:

pattern = re.compile("HP ([a-z]+) (\d+[a-z]?(?: \w+)?) .*?\((.*)\)", re.IGNORECASE)

就这么一分为二

text="""HP EliteDesk 800 G1 SFF (H3S08US#ABA)
HP Pro 3400 Series MT (H3S08US#ABA)
HP EliteBook 8460p (H3S08US#ABA)"""

for line in text.split("\n"):
    words = line.split()
    hp, hp_line = words[:2]
    hp_model = ''.join(words[2:-1][:2])
    serial = words[-1]
    print "Production line : %s" % hp_line
    print "Production model : %s" % hp_model
    print "Serial number : %s" % serial
    print

相关问题 更多 >