【问题标题】:What's the most elegant way to re-write a bunch of these python functions?重写这些 python 函数的最优雅的方法是什么?
【发布时间】:2018-03-14 01:49:59
【问题描述】:

我有一堆看起来像这样的文本处理函数:

def sample_func(txt=None, file_input=None, file_output=None):
    if txt is None:
        raw_txt = get_text_from_file(file_input)
    else:
        raw_txt = txt

    cleaned_txt = re.sub(r'\n\n', '\n', raw_txt)

    if file_output is not None:
        write_text_to_file(cleaned_txt, file_output)
    return cleaned_txt

当你有 10 个以上的这些时,它会变得非常乏味。

此函数用于清理一长串文件,因此参数将在运行时提供并指向字符串(对于参数txt)或文件名(对于参数file_inputfile_output )。我曾考虑过使用装饰器,但不知道该怎么做。

我想到的一种方法是输入一个参数函数来执行实际的清洁,即:

def clean_text_with_cleaner(cleaner_func, txt=None, file_input=None, file_output=None):
    if txt is None:
        raw_txt = get_text_from_file(file_input)
    else:
        raw_txt = txt

    cleaned_txt = cleaner_func(raw_txt)

    if file_output is not None:
        write_text_to_file(cleaned_txt, file_output)
    return cleaned_txt

还有比这更优雅的方式吗?

【问题讨论】:

    标签: python decorator python-decorators


    【解决方案1】:
    def sample_func(txt=None, file_input=None, file_output=None):
        raw_txt = txt or get_text_from_file(file_input) 
        cleaned_txt = re.sub(r'\n\n', '\n', raw_txt)    
        write_text_to_file(cleaned_txt, file_output) # handle file_output is None in this other function
        return cleaned_txt
    

    可能被某些人认为更清洁...其他人可能不喜欢这种方法...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-22
      • 1970-01-01
      • 2010-10-17
      • 1970-01-01
      • 1970-01-01
      • 2020-04-22
      • 1970-01-01
      相关资源
      最近更新 更多