簡體   English   中英

將多個函數的列表作為參數傳遞給另一個 python function

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

我已經創建了用於文本預處理的函數,即 f1:remove_punctuation、f2:remove_stop_words、f3:tokenize_doc。 我想創建另一個 function, f4,它允許用戶選擇任何一個/任何 2/所有函數 f1、f2 和 f3(作為參數接受)並作為 f4 的一部分執行。

目前,下面的代碼在 f4 中執行函數 f1、f2 和 f3,因為 f4 的參數部分沒有可用參數。 有人可以幫我修改代碼嗎:

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')

注意:TP 是一個 package,它是從一個名為 TextPreprocessor 的 class 中具有 f1、f2 和 f3 的文件創建的,其結構如下:

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

編寫一個 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