Home > Back-end >  how to convert a string into an array of variables
how to convert a string into an array of variables

Time:01-18

how can i take a string like this

string = "image1 [{'box': [35, 0, 112, 36], 'score': 0.8626706004142761, 'label': 'FACE_F'}, {'box': [71, 80, 149, 149], 'score': 0.8010843992233276, 'label': 'FACE_F'}, {'box': [0, 81, 80, 149], 'score': 0.7892318964004517, 'label': 'FACE_F'}]"

and turn it into variables like this?

filename = "image1"
box = [35, 0, 112, 36]
score = 0.8010843992233276
label = "FACE_F"

or if there are more than one of box, score, or label

filename = "image1"
box = [[71, 80, 149, 149],  [35, 0, 112, 36], [0, 81, 80, 149]]
score = [0.8010843992233276, 0.8626706004142761, 0.7892318964004517]
label = ["FACE_F", "FACE_F", "FACE_F"]

this is how far i've gotten

log = open(r'C:\Users\15868\Desktop\python\log.txt', "r")
data = log.readline()
log.close()

print(data)

filename = data.split(" ")[0]
info = data.rsplit(" ")[1]

print(filename)
print(info)

output

[{'box':
image1

CodePudding user response:

Here is how I would do it:

import ast
string = "image1 [{'box': [35, 0, 112, 36], 'score': 0.8626706004142761, 'label': 'FACE_F'}, {'box': [71, 80, 149, 149], 'score': 0.8010843992233276, 'label': 'FACE_F'}, {'box': [0, 81, 80, 149], 'score': 0.7892318964004517, 'label': 'FACE_F'}]"
filename, data = string.split(' ', 1)
data = ast.literal_eval(data)
print(filename)
print(data)

Output:

image1
[{'box': [35, 0, 112, 36], 'score': 0.8626706004142761, 'label': 'FACE_F'}, {'box': [71, 80, 149, 149], 'score': 0.8010843992233276, 'label': 'FACE_F'}, {'box': [0, 81, 80, 149], 'score': 0.7892318964004517, 'label': 'FACE_F'}]

(updated to follow your example of combining the keys): From there I'd just write some simple code, something like:

box = []
score = []
label = []
for row in data:
    box.append(row['box'])
    score.append(row['score'])
    label.append(row['label'])

To unpack that data there are fancier ways but that is the most straight forward, for example:

box, score, label = zip(*{ x.values() for x in data })
  • Related