首页 > 解决方案 > 从大量停用词中删除停用词

问题描述

我正在对数据集进行一些 NLP,并且正在尝试删除停用词。

我没有使用内置的 nltk 停用词,而是使用自定义停用词列表(大约 10k 个不同语言的单词)

我首先定义了以下函数

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

我的问题是处理时间很长,那么有没有更快的方法来做到这一点?

标签: pythonmachine-learningnlp

解决方案


包含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

推荐阅读