将函数列表应用于单个动态字符串

2024-04-19 12:11:06 发布

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

我正在创建一个小型python应用程序,将文件名格式化为一组规则。我很难找到一种方法来将常规格式函数列表应用于同一字符串。我想应用一个函数,然后是另一个,然后是另一个。你知道吗

我设法找到了一种可行的方法,但我觉得它非常笨拙。你知道吗

这里我有一个列表列表,其中包括一个函数和一个kwargs字典。(所有这些函数都有一个字典中没有的“text”参数)。你知道吗

functions = [
[SRF.change, {'old': '.', 'new': ' '}],
[SRF.surround, {'value': SU.get_year}],
[SRF.remove, {'chars': '[],'}],
[SRF.capitalize_words, {}],
[SRF.remove_including, {'value': 'mp4'}]]

然后将其传递到custom_rename函数中。它在函数列表上循环并将其应用于“text”变量。如您所见,每次调用func(text, **kwargs)时,变量都会更改。你知道吗

def custom_rename(text, functions_list):

    # Apply a list of functions to a string
    for func_list in functions_list:
        func = func_list[0]  # Function
        kwargs = func_list[1]  # Dictionary
        try:
            text = func(text, **kwargs)
        except AttributeError:
            pass

    return text

有没有更优雅的方法?一、 例如,不喜欢我必须知道函数在[0]位置,字典在[1]位置。你知道吗


Tags: 方法函数text应用程序列表字典valuecustom
1条回答
网友
1楼 · 发布于 2024-04-19 12:11:06

与存储[function, arguments]列表不同,您可以使用^{}创建具有已烘焙参数的可调用项:

from functools import partial

functions = [
    partial(SRF.change, old='.', new=' '),
    partial(SRF.surround, value=SU.get_year),
    partial(SRF.remove, chars='[],'),
    SRF.capitalize_words,
    partial(SRF.remove_including, value='mp4')
]

现在您的custom_rename函数可以简化为:

def custom_rename(text, functions_list):
    # Apply a list of functions to a string
    for func in functions_list:
        try:
            text = func(text)
        except AttributeError:
            pass

    return text

相关问题 更多 >