0

I want to give same number to the same string name and save it to text file.

For example if there are multiple strings name "Ball" from filename, then I will give this string number 0. Another example, if I have multiple strings name "Square" from filename, then I will give this string number 1. And so on.

I tried using os.path.walk and splitting the text but still have no idea how to add the number and save it to text file

with open("check.txt", "w") as a:
    for path, subdirs, files in os.walk(path):
        for i, filename in enumerate(files):

            #the filename have underscore to separate the space
            #for example Ball_red_move

            mylist = filename.split("_") 

            #I tried to take the first string name only after splitting, here 
            #for example "Ball"

            k = mylist[0]

            #After this I don't have idea to add number when the string name 
            #is same and also save it to txt file with the directory name

This is my expected result:

Check/Ball_red_move_01 0

Check/Ball_red_move_02 0

Check/Ball_red_move_03 0


Check/Square_jump_forward_01 1

Check/Square_jump_forward_02 1

Check/Square_jump_forward_03 1

1 Answer 1

1

You might like to do something like this:

Prepare a dictionary to map the string to some labeling numbers and check if the string is present.

object_map = {'Ball': 0, 'Square': 1}

def get_num_from_string(x):
    for i in object_map:
        if i in x:
            return object_map[i]

A = ['Check/Ball_red_move_01', 'Check/Square_jump_forward_01']

for i in A:
    print(i + ' '+str(get_num_from_string(i)))

This produces

Check/Ball_red_move_01 0
Check/Square_jump_forward_01 1

A few thing for you to consider, what do you want to do none of the string appears and also what do you want to do if multiple strings appear.

Sign up to request clarification or add additional context in comments.

Comments

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.