首页 > 解决方案 > How to categorise components in a list of strings

问题描述

I have a list of strings which I need to go through and categorise the components. The components are in categories in the list however I'm not sure where to start.

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;']

The output I expect to get is;

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

C500 only needs to be defined once.

I am able to get a list of just the components but have no idea how to get what category they are in.

标签: pythonpython-2.7

解决方案


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

前任:

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

推荐阅读