如何检查字符串列表是否具有相同的名称?

时间:2019-05-11 20:55:41

标签: python string text label

我想将多个字符串分类为一些标签。例如,如果字符串中的单词为“ 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

1 个答案:

答案 0 :(得分:0)

我将通过创建一个对应于标签值的标签名称字典来解决这个问题。

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开始计数)的标签。

相关问题