社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

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

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

例如,如果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 年前
Siong Thye Goh
Reply   •   1 楼
Siong Thye Goh    7 年前

你可能想这样做:

准备一个字典,将字符串映射到一些标签号,并检查字符串是否存在。

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)))

这就产生了

Check/Ball_red_move_01 0
Check/Square_jump_forward_01 1

有几件事要考虑,你想做什么,没有一个字符串出现,也要做什么,如果多个字符串出现。