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

2024-10-02 02:43:02 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上,我计划做的是从我的目录中的每个图像中提取文件名,并将其存储在一个列表中,以便与该图像本身链接,用于对象检测和预测关键字。例如,文件名为animal_cat_kowai.png,因此我希望我的列表将[animal,cat,kowai]链接到该文件。 这是我的代码: 仅当我在此目录中有70个图像时,才会显示单词“cat”。hon


Tags: 文件对象代码图像目录列表png链接
2条回答

如果您只想根据“\ux”分割文件名, 如果 filename=“animal\u cat\u kowai.png”

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

这将导致您的_lisr=[“动物”、“猫”、“kowai”]

我认为list不适合链接。相反,使用dict

首先导入所需的模块

from pathlib import Path

启动变量

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

填充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

相关问题 更多 >

    热门问题