Py学习  »  Python

如何在python中为同一字符串添加相同的数字?

Bob Adi Setiawan • 6 年前 • 1947 次点击  

我想给相同的字符串名赋予相同的数字并将其保存到文本文件中。

例如,如果filename中有多个名为“ball”的字符串,那么我将给这个字符串编号0。另一个例子,如果我有来自filename的多个字符串名“square”,那么我将给这个字符串编号1。等等。

我试过使用os.path.walk和拆分文本,但仍然不知道如何添加数字并将其保存到文本文件中

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

这是我的预期结果:

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
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/46897
文章 [ 1 ]  |  最新文章 6 年前