ここに別のアプローチがあります。
関数合成に関するウィキペディアの記事のファーストクラス合成セクションに示されているような一般的な関数を書くことができます。この記事とは異なり、関数は への呼び出しにリストされている順序で適用されることに注意してください。compose()
try:
from functools import reduce # Python 3 compatibility
except:
pass
def compose(*funcs, **kwargs):
"""Compose a series of functions (...(f3(f2(f1(*args, **kwargs))))) into
a single composite function which passes the result of each
function as the argument to the next, from the first to last
given.
"""
return reduce(lambda f, g:
lambda *args, **kwargs: f(g(*args, **kwargs)),
reversed(funcs))
これが何をするかを示す簡単な例です:
f = lambda x: 'f({!r})'.format(x)
g = lambda x: 'g({})'.format(x)
h = lambda x: 'h({})'.format(x)
my_composition = compose(f, g, h)
print my_composition('X')
出力:
h(g(f('X')))
モジュール内の一連の関数に適用する方法は次のとおりです。
my_composition = compose(remove_tables, clean_text_passage, replace,
count_words, risk_count)
with open('filing2.txt') as input:
riskcount = my_composition(input.read())