简体   繁体   English

将多个函数的列表作为参数传递给另一个 python function

[英]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.我已经创建了用于文本预处理的函数,即 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.我想创建另一个 function, f4,它允许用户选择任何一个/任何 2/所有函数 f1、f2 和 f3(作为参数接受)并作为 f4 的一部分执行。

Currently, the below code executes both the functions f1,f2 & f3 inside f4 as no parameter is available in argument section of f4.目前,下面的代码在 f4 中执行函数 f1、f2 和 f3,因为 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:注意:TP 是一个 package,它是从一个名为 TextPreprocessor 的 class 中具有 f1、f2 和 f3 的文件创建的,其结构如下:

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.编写一个 function 获取用户选择,并根据需要调用其他函数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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