从大量停用词列表中移除停用词耗时过长

我在处理一个数据集进行自然语言处理,并尝试移除停用词。

我没有使用nltk内置的停用词列表,而是使用了一个自定义的停用词列表(包含大约10,000个不同语言的词)。

我首先定义了以下函数:

def clean_text(text):    text = ''.join([word.lower() for word in text if word not in string.punctuation])    tokens = re.split('\W+', text)    text = [lm.lemmatize(word) for word in tokens if word not in stopwords]    return text

然后我将其应用到数据框中,如下所示:

df_train['clean_text'] = df_train['question_text'].apply(lambda x: clean_text(x))

我的问题是处理速度非常慢,有没有更快的方法来做这件事?


回答:

对字符串和列表进行包含检查(x in data_structure)是线性操作。这意味着string.punctuation会在你的初始text中的每个字符上进行迭代,而stopwords会在每个标记上进行迭代。将它们都转换为集合可以使这些检查成为常数操作:

punct = set(string.punctuation)stopwords = set(stopwords)def clean_text(text):    text = ''.join(char.lower() for char in text if char not in punct)    tokens = re.split('\W+', text)    text = [lm.lemmatize(word) for word in tokens if word not in stopwords]    return text

一些参考资料:

  1. https://wiki.python.org/moin/TimeComplexity#set
  2. https://wiki.python.org/moin/TimeComplexity#list

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注