我在处理一个数据集进行自然语言处理,并尝试移除停用词。
我没有使用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
一些参考资料: