首页 > 解决方案 > 如何检查字符串列表是否同名?

问题描述

我想将多个字符串分类为一些标签。例如,如果字符串中有一个单词“Cat”,那么我会给它标签编号 1。再比如,如果我有一个字符串“Dog”,那么我会给它标签 2,以此类推。

我试过比较字符串,但它给出了错误。

我使用了 import os 但仍然不知道在上面添加标签。

import os
path = "check"
dirList = os.listdir(path)


with open("check.txt", "w") as a:
    for path, subdirs, files in os.walk(path):
        for filename in files:
            #print(i)
            mylist = filename.split("_")

            #for mlist in mylist:

预期结果:

Cat_0 0
Cat_1 0
Cat_2 0
Cat_3 0
Dog_0 0
Dog_1 0
Dog_2 0
Dog_3 0

标签: pythonstringtextlabel

解决方案


我将通过创建与其标签值相对应的标签名称字典来解决此问题。

labels = {
    'Cat': 0,
    'Dog': 1,
    //etc
}

然后,当您浏览目录中的每个文件时,对于每个文件,请考虑文件名是否包含标签名称。如果是这样,给它标签值。您也可以将此逻辑提取到它自己的函数中,这样会更清晰。

def find_label(labels, to_label): #'labels' is your dictionary of labels, to_label is the string you want to label.
    for key in labels.keys():
        if key in to_label:
            return labels[key]
    return -1 #If you've made it here, none of your labels apply

一旦你有了这个函数,你只需调用它并在每次有一个要标记的新文件时使用结果。

for filename in files:
    label = find_labels(label, filename)
    #Write your label to a file or whatever you want to do with it.

如果你有太多的标签,把字典写出来是个问题,那么用 python 创建字典。

label_names = [] #A list of all your label names that you've read into a list
labels = {}
count = 0
for name in label_names:
    labels[name] = count
    count+=1

现在,您的标签字典包含所有具有唯一标签值的标签,这些标签值从 0 开始计数。


推荐阅读