0

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
1
  • 2
    Creating variables dynamically is usually a bad idea. Instead of such dynamically generated variables you can create a dictionary with keys like 'box' and 'score'. Commented Jan 17, 2023 at 22:51

1 Answer 1

3

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 })
Sign up to request clarification or add additional context in comments.

2 Comments

It looks like this person wants each of the keys to also be variables. One way to go about that is to use the globals() dictionary and insert the key string to be equal to the value. e.g. globals()['box'] = [35, 0, 112, 36].
I appreciate that you both a) answer the question literally and b) show what is probably the more sensible way to do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.