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

时间:2019-08-09 10:04:31

标签: python python-2.7

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

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仅需要定义一次。

我只能获得组件列表,但不知道如何获取它们所在的类别。

2 个答案:

答案 0 :(得分:2)

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

例如:

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

答案 1 :(得分:2)

假设格式与显示的完全一样,它只是一个分割序列和一个字典:

In [10]: 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;''']

In [11]: d = {} 
    ...: for s in lst: 
    ...:     for typelist in s.split('\n\n'): 
    ...:         Type, *elements = typelist.split('\n') 
    ...:         for element in elements: 
    ...:             name = element.strip().split()[0] 
    ...:             d[name] = Type 
    ...:                                                                                  

In [12]: d                                                                                
Out[12]: 
{'C500': 'CAPACITOR',
 'C501': 'CAPACITOR',
 'R100': 'RESISTOR',
 'R101': 'RESISTOR',
 'C507': 'CAPACITOR',
 'TP100': 'CONNECTOR',
 'TP101': 'CONNECTOR'}