简体   繁体   English

使用“_”拆分文件名并在python中转换列表中的单词

[英]Splitting filename using "_ " and converting the words in a list in python

Basically what I plan to do is that I want to extract the filename from each image in my directory and store it in a list to be linked with that image itself for object detection and predicting keywords.基本上我打算做的是我想从我目录中的每个图像中提取文件名并将其存储在一个列表中,以与该图像本身链接以进行对象检测和预测关键字。 For example, the filename is animal_cat_kowai.png, so I want my list to have [animal, cat,kowai] linked to the file.例如,文件名是animal_cat_kowai.png,所以我希望我的列表有[animal, cat,kowai] 链接到文件。 This is my code : This displays the word 'cat' only while I have 70 images in this directory.这是我的代码:仅当我在此目录中有 70 张图像时才显示“cat”一词。 hon亲爱的

if you just want the name of the file to be split based on "_", if filename = "animal_cat_kowai.png"如果只想根据“_”分割文件名,if filename = "animal_cat_kowai.png"

your_list = filename[:filename.index(".")].split("_")

This would result in your_lisr = ["animal","cat","kowai"]这将导致 your_lisr = ["animal","cat","kowai"]

I think that list is not suitable for the link.我认为该list不适合链接。 Insted, use dict . Insted,使用dict

First import required modules.首先导入所需的模块。

from pathlib import Path

Initiate variable.初始化变量。

image_dict = {}  # handle name and link
all_file = list(Path().iterdir())  # get all file in current directory

Populate image_dict .填充image_dict

for f in all_file:
    extension = str(f).split(".")[-1]
    filename = str(f).split("." + extension)[0]

    if extension in ["png", "jpeg"]:  # In case of there is other file that's no an image
        part_name = filename.split("_")  # Get keywords from filename

        for pn in part_name:  # Append a link from each keyword
            if image_dict.get(pn, None) is not None:
                image_dict[pn].append(f.resolve())
            else:
                image_dict[pn] = [f.resolve()]

print(image_dict)  # This is the result

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM