gpt4 book ai didi

python - 如何对字符串列表中的组件进行分类

转载 作者:太空宇宙 更新时间:2023-11-04 09:26:24 24 4
gpt4 key购买 nike

我有一个字符串列表,我需要对其进行检查并对组件进行分类。这些组件在列表中的类别中,但我不确定从哪里开始。

lst = [
'CAPACITOR
C500 1u PN"1";
C501 1u PN"2";

RESISTOR
R100 10 PN"10";
R101 10 PN"11";'

,

'CAPACITOR
C500 1u PN"1";
C507 1u PN"2";

CONNECTOR
TP100 NT;
TP101 NT;']

#Above formatted as it is easier to see

lst = [ 'CAPACITOR\n C500 1u PN"1";\n C501 1u PN"2";\n\nRESISTOR\n R100 10 PN"10";\n R101 10 PN"11";\n' , '\nCAPACITOR\n C500 1u PN"1";\n C507 1u PN"2";\n\nCONNECTOR\n TP100 NT;\n TP101 NT;']

我期望得到的输出是;

C500 , Capacitor
C501 , Capacitor
R100 , Resistor
R101 , Resistor
C507 , Capacitor
TP100 , Connector
TP101 , Connector

C500 只需定义一次。

我只能得到一个组件列表,但不知道如何得到它们属于哪个类别。

最佳答案

这是一种使用正则表达式的方法。

例如:

import re

lst = [ 'CAPACITOR\n C500 1u PN"1";\n C501 1u PN"2";\n\n RESISTOR\n R100 10 PN"10";\n R101 10 PN"11";\n ' , '\n CAPACITOR\n C500 1u PN"1";\n C507 1u PN"2";\n \n CONNECTOR\n TP100 NT; \n TP101 NT;']
result = []
for i in lst:
for j in i.splitlines():
if j.strip():
category = re.match(r"\s*(\b[A-Z]+\b)", j) #Check if line has category --> All Capital letters
if category:
result.append([category.group(1)])
else:
component = re.match(r"\s+(\b[A-Z0-9]+\b)", j) #Check if line has component --> Capital letter and int.
if component:
result[-1].append(component.group(1))

for i in result:
category = i[0]
for component in i[1:]:
print(component, category)

输出:

C500 CAPACITOR
C501 CAPACITOR
R100 RESISTOR
R101 RESISTOR
C500 CAPACITOR
C507 CAPACITOR
TP100 CONNECTOR
TP101 CONNECTOR

关于python - 如何对字符串列表中的组件进行分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57427786/

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