gpt4 book ai didi

python - 使用正则表达式查找型号

转载 作者:太空宇宙 更新时间:2023-11-03 19:40:49 26 4
gpt4 key购买 nike

我有以下列表,我正在尝试使用正则表达式提取项目型号

names=[
'Honda Engine GX200 6.5HP 2.43" x 3/4" Crankshaft',
'Honda New GX390 Engine Standard 1" Crank, Electric Start, Oil Alert',
'Genuine Honda 79160-SHJ-A41 Temperature Driver Motor Assembly',
'Auto Express Long Block Engine Crankcase with Cylinder Head Valves Fits Honda GX200 6.5 HP',
'Honda 08207-10W30 PK2 Motor Oil'
]

型号只能包含大写字母、-、数字

for name in names:
model_num=re.search('([A-Z]+\d+\-[A-Z]*)',name).groups()[0]

我的正则表达式并不总是有效。预期输出是:

['GX200','GX390','79160-SHJ-A41','GX200','08207-10W30']

如果有比正则表达式更简单的方法也可以使用,我们将不胜感激。

最佳答案

使用re.compile可以稍微提高速度:

find_model = re.compile(
"""
[A-Z\d\-]+
(?![a-z]) # Check that next char isn't lowercase to avoid getting false-positive head letter only
""",
re.VERBOSE,
)
for name in names:
result = find_model.search(name)
if result:
model_num = result.group(0)
print(model_num)

关于python - 使用正则表达式查找型号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60436885/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com