【发布时间】: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_input、file_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