【问题标题】:Python Duplicate namingPython重复命名
【发布时间】:2021-11-02 07:24:45
【问题描述】:

目标是为重复字符串创建一个命名系统。

如果名称是 hotdog.jpg 并且我想复制一个并且下一个字符串是 hotdog_1.jpg。等等。但我面临的问题是,如果你复制 hotdog_1.jpg,我们会得到 hotdog_1_1.jpg。我试图检查字符串是否以“(下划线)+数字”结尾。但问题是字符串也可能有“(下划线)+数字+数字”。比如 hotdog_13.jpg。

有什么好的方法可以实现吗?

for current_image_name in self.images_names:
    extension = os.path.splitext(current_image_name)[1]
    current_image_name = os.path.splitext(current_image_name)[0]

    if current_image_name[-2] == '_' and current_image_name[-1].isdigit():
        self.images_names.insert(self.current_index + 1, current_image_name[:-1] + str(int(self.images_names[self.current_index][-1]) + 1) + extension)
        name_change = True

if not name_change:
    self.images_names.insert(self.current_index + 1, self.images_names[self.current_index] + '_1')

【问题讨论】:

  • 稍微澄清一下,当文件名为 hotdog_1.jpg 时,您期望会发生什么?您是否期待名称冲突(已存在的文件)?
  • 是的,没错。所以所有的文件名都存储在一个列表中。因此,如果我想复制列表中的当前字符串,列表中的下一项将是 hotdog_1.jpg,如果您复制它,我们将得到 hotdog_2.jpg 等等...

标签: python string filenames


【解决方案1】:

你可以用一个简单的方法来做这件事,它可以做一些字符串魔术。

EDITED 在阅读了有关问题的 cmets 后。添加了处理列表的方法

代码

def inc_filename(filename: str) -> str:
    if "." in filename:
        # set extension
        extension = f""".{filename.split(".")[-1]}"""
        # remove extension from filename
        filename = ".".join(filename.split(".")[:-1])
    else:
        # set extension to empty if not included
        extension = ""
    try:
        # try to set the number
        # it will throw a ValueError if it doesn't have _1
        number = int(filename.split("_")[-1]) +1
        newfilename = "_".join(filename.split("_")[:-1])
    except ValueError:
        # catch the ValueError and set the number to 1
        number = 1
        newfilename = "_".join(filename.split("_"))
    return f"{newfilename}_{number}{extension}"


def inc_filelist(filelist: list) -> list:
    result = []
    for filename in filelist:
        filename = inc_filename(filename)
        while filename in filelist or filename in result:
            filename = inc_filename(filename)
        result.append(filename)
    return result


print(inc_filename("hotdog_1"))
print(inc_filename("hotdog"))
print(inc_filename("hotdog_1.jpg"))
print(inc_filename("hotdog.jpg"))
print(inc_filename("ho_t_dog_15.jpg"))
print(inc_filename("hotdog_1_91.jpg"))

filelist = [
    "hotdog_1.jpg",
    "hotdog_2.jpg",
    "hotdog_3.jpg",
    "hotdog_4.jpg"
]

print(inc_filelist(filelist))

输出

hotdog_2
hotdog_1
hotdog_2.jpg
hotdog_1.jpg
ho_t_dog_16.jpg
hotdog_1_92.jpg
['hotdog_5.jpg', 'hotdog_6.jpg', 'hotdog_7.jpg', 'hotdog_8.jpg']

【讨论】:

    猜你喜欢
    • 2018-03-04
    • 2021-04-29
    • 2016-07-22
    • 2018-05-08
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 2016-03-25
    相关资源
    最近更新 更多