python - 是否有比此代码更快的替代方法来删除 Pandas 中的停用词和标点符号?

标签 python pandas nltk

我使用的代码似乎太慢了,也许有替代方案。

在 Pandas 中,我标记了数据框列“描述”并制作了一个要删除的停用词和标点符号列表,然后尝试删除无用的词。

import numpy as np
import pandas as pd
import nltk
import string
nltk.download("stopwords")
nltk.download('punkt')

df2 = pd.read_csv('xxx')

在清理等之后,最终得到大约 135.000 行并且没有空值

description points  price
0   This tremendous 100% varietal wine hails from ...   96  235.0
1   Ripe aromas of fig, blackberry and cassis are ...   96  110.0
2   Mac Watson honors the memory of a wine once ma...   96  90.0
3   This spent 20 months in 30% new French oak, an...   96  65.0
4   This is the top wine from La Bégude, named aft...   95  66.0

然后分词

df2['description'] = df2.apply(lambda row: 
nltk.word_tokenize(row['description']), axis=1)
df2.head()

tokenize 非常快。现在定义无用的词:

useless_words = nltk.corpus.stopwords.words("english") + 
list(string.punctuation)

现在尝试使用相同的技巧从 df2['description'] 中删除无用的词

df2['description'] = df2.apply(lambda row: [word for word in 
df2['description'] if not word in useless_words], axis=1)

我预计这会更快,但需要时间来计算。我是编码的新手,所以我想也许你们知道一种替代方法来处理这个问题并减少计算时间。也可能我没有做对,我不知道,所以我提前询问并感谢。

最佳答案

你试过吗?

df2["description"] = df2["description"].str.lower()
df2["description"] = df2["description"].str.replace("|".join(useless_words), "")

关于python - 是否有比此代码更快的替代方法来删除 Pandas 中的停用词和标点符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55666935/

相关文章:

python - 如何解决 nltk.classify ClassifierI 中的 NotImplementedError?

python - 为什么 webapp.WSGIApplication 的实例总是在谷歌应用引擎代码中定义为全局变量?

Python广度优先搜索矩阵打印路径

python - 来自 dialogAction(Python) 的空响应

python - 在 Pandas 中一次在列中显示常用值

Python pandas 对多列执行相同的聚合

python - 将应用操作中的对象合并到 PANDAS 中的数据帧

python - NLTK 停用词返回错误 "LazyCorpusLoader is not callable"

python - MAXent分类器NLTK输出理解

python - NLTK 替换停用词