Home > Net >  How do I strip out only item in file for name: and it value to the right only and put it in list in
How do I strip out only item in file for name: and it value to the right only and put it in list in

Time:09-08

item {
  name: "bicycle"
  id: 1
  display_name: "bicycle"
}
item {
  name: "car"
  id: 2
  display_name: "car"
}
item {
  name: "motorcycle"
  id: 3
  display_name: "motorcycle"
}

need a list of

["bicycle","car", "motorcycle"]

CodePudding user response:

Ok I figured it out:

result_list = []  

names_path= "object-detect.pbtxt"

with open(names_path) as f:
    names_list=f.readlines()
for ix, line in enumerate(names_list):
    names_list[ix]= names_list[ix].strip('\n')
    if (names_list[ix].find('name:') != -1):
        position = names_list[ix].find('"')
        result_list.append(names_list[ix][position:].strip('"'))

print(result_list)

CodePudding user response:

If all you care about is the lines that contain name: ..., then you can use a regex on the entire file:

import re

names = []
with open(filename) as f:
    for line in f:
        line = line.strip()  # Strip leading and trailing whitespace
        names.extend(re.findall(r'^name: "(.*)"$', line))

Which gives:

names = ['bicycle', 'car', 'motorcycle']

An explanation of the regex try it online:

^name: "(.*)"$

^                 - Start of line (since we stripped out leading whitespace)
 name: "          - Literally name, followed by a colon, followed by a quote
        (  )      - Capturing group 
         .*       - Any number of any character
            "     - The closing quote
             $    - End of line
  • Related