3

次のように、モジュールでいくつかの関数を実行する必要があります。

mylist = open('filing2.txt').read()
noTables = remove_tables(mylist)
newPassage = clean_text_passage(noTables)
replacement = replace(newPassage)
ncount = count_words(replacement)
riskcount = risk_count(ncount)

すべての機能を一度に実行する方法はありますか? すべての関数を大きな関数にして、その大きな関数を実行する必要がありますか?

ありがとう。

4

4 に答える 4

2

使用されている共通シーケンスを実行するモジュールで新しい関数を作成する必要があります。これには、どの入力引数が必要で、どのような結果が返されるかを理解する必要があります。あなたが投稿したコードを考えると、新しい関数は次のようになるかもしれません-私はあなたが興味を持っているかもしれない最終結果について推測しましたwith。 .

def do_combination(file_name):
    with open(file_name) as input:
        mylist = input.read()
    noTables = remove_tables(mylist)
    newPassage = clean_text_passage(noTables)
    replacement = replace(newPassage)
    ncount = count_words(replacement)
    riskcount = risk_count(ncount)

    return replacement, riskcount

使用例:

replacement, riskcount = do_combination('filing2.txt')
于 2012-09-02T16:51:38.957 に答える
1

これらの行を Python (.py) ファイルに保存するだけで、簡単に実行できます。

それとも、ここで何か不足していますか?

ただし、関数を作成するのも簡単です。

def main():
    mylist = open('filing2.txt').read()
    noTables = remove_tables(mylist)
    newPassage = clean_text_passage(noTables)
    replacement = replace(newPassage)
    ncount = count_words(replacement)
    riskcount = risk_count(ncount)

main()
于 2012-09-02T16:40:02.380 に答える
1

私が理解している限り、使用には関数合成が必要です。Python stdlib にはこのための特別な関数はありませんが、関数を使用してこれを行うことができますreduce

funcs = [remove_tables, clean_text_passage, replace, count_words, risk_count]
do_all = lambda args: reduce(lambda prev, f: f(prev), funcs, args)

として使用

with open('filing2.txt') as f:
    riskcount = do_all(f.read()) 
于 2012-09-02T17:01:05.377 に答える
0

ここに別のアプローチがあります。

関数合成に関するウィキペディアの記事のファーストクラス合成セクションに示されているような一般的な関数を書くことができます。この記事とは異なり、関数は への呼び出しにリストされている順序で適用されることに注意してください。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())
于 2012-09-02T19:24:41.710 に答える