简体   繁体   中英

Passing a list of multiple functions as a parameter in another python function

I have created functions for text preprocessing namely f1: remove_punctuation, f2: remove_stop_words, f3: tokenize_doc. I want to create another function, f4 that allows user to choose any one/any 2/all functions f1, f2 & f3 (accepted as a parameter) and executed as part of f4.

Currently, the below code executes both the functions f1,f2 & f3 inside f4 as no parameter is available in argument section of f4. Can someone please help me modifying the code:

from txt_preprocessing.text_preprocessing import TextPreprocessor as TP
import pandas as pd
def read_input_from_file(filename):
    df=pd.read_csv(filename)
    function_list={TP.remove_punctuation:'remove_punctuation', TP.remove_stop_words:'remove_stop_words', TP.tokenize_doc:'tokenize_doc' }
    for func_i in function_list: 
        df['X']=df['X'].apply(lambda x: func_i(x,return_var_type="string"))
    df.to_csv('text_classification_output.csv')
    return df

read_input_from_file('text_classification_input.csv')

Note: TP is a package created from a file having f1, f2 & f3 in a class named TextPreprocessor and has a structure as:

class TextPreprocessor:
    .....
    def remove_punctuation
      .......
    def remove_stop_words
      .......
    def tokenize_doc
      .......

Write a function that gets the user choice, and calls the other functions as appropriate.

def user_choice(x, return_var_type):
    choice = input("Remove punctuation, stop words, or both (p/s/b):")
    if choice in ['p', 'b']:
        x = TP.remove_punctuation(x, return_var_type)
    if choice in ['s', 'b']:
        x = TP.remove_stop_words(x, return_var_type)
    return x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM