Skip to main content
 首页 » 编程设计

python之如何定义将在 python 类中函数的每次迭代中使用的变量

2025年05月04日14yyy_WW

我有一个定义函数 define_stop_words 的类,该函数返回字符串标记列表。然后,我将另一个名为 remove_stopwords 的函数应用于包含文本的 pandas 数据帧 df,该函数将原始 utf8 文本作为输入。代码看起来像这样

class ProcessText: 
 
    def __init__(self, flag): 
        self.flag = flag # not important for this question 
 
    def define_stop_words(self): 
        names = ['john','sally','billy','sarah'] 
        stops = ['if','the','in','then','an','a'] 
        return stops+names 
 
    def remove_stopwords(self, text): 
        return [word for word in text if word not in self.define_stop_words()] 
 
 
 import pandas as pd 
 df = pd.read_csv('data.csv') 
 parse = ProcessText(flag=True) 
 df['text'] = df['text'].apply(parse.remove_stopwords()) 

我的问题是,remove_stopwords 函数是否每次都会调用并定义 define_stop_words 返回的变量 - 对于 text 中的每个单词df 中的每一行(基本上是每次迭代)?

如果是这种情况,我不希望它这样运行,因为它会非常缓慢且效率低下。我想定义 define_stop_words once 返回的变量,几乎就像 ProcessText 类中的“全局变量”,然后在中使用该变量remove_stopwords 多次(针对 df 中的每个单词和行)。

有没有办法做到这一点 - 应该这样做吗?这种情况下的最佳做法是什么?

请您参考如下方法:

您可以将这些名称分配给类变量,如

class ProcessText: 
   names = ['john','sally','billy','sarah'] 
   stops = ['if','the','in','then','an','a'] 
 
   def __init__(self, flag): 
       self.flag = flag # not important for this question 
 
   def remove_stopwords(self, text): 
       return [word for word in text if word not in self.names + self.stops] 
 
 
import pandas as pd 
df = pd.read_csv('data.csv') 
parse = ProcessText(flag=True) 
df['text'] = df['text'].apply(parse.remove_stopwords()) 

那些类变量被所有实例继承。每次创建新实例时,__init__() 方法中的赋值将导致多次赋值。