python - 使用 NLTK 删除停用词时对象没有属性

标签 python pandas nltk

我正在尝试从 pandas DataFrame 的 NLTK 停用词集合中删除停用词,该数据框由 Python 3 中的文本数据行组成:

import pandas as pd
from nltk.corpus import stopwords

file_path = '/users/rashid/desktop/webtext.csv'
doc = pd.read_csv(file_path, encoding = "ISO-8859-1")
texts = doc['text']
filter = texts != ""
dfNew = texts[filter]

stop = stopwords.words('english')
dfNew.apply(lambda x: ' '.join([word for word in x.split() if word not in (stop)]))

我收到此错误:

'float' object has no attribute 'split'

最佳答案

听起来你的文本中有一些数字,它们导致 Pandas 变得有点太聪明了。将 dtype 选项添加到 pandas.read_csv() 以确保列 text 中的所有内容都作为字符串导入:

doc = pd.read_csv(file_path, encoding = "ISO-8859-1", dtype={'text':str})

一旦你的代码开始工作,你可能会注意到它很慢:在列表中查找内容效率低下。将您的停用词放入这样的集合中,您会对加速感到惊讶。 (in 运算符适用于集合和列表,但速度有很大差异。)

stop = set(stopwords.words('english'))

最后,将x.split()更改为nltk.word_tokenize(x)。如果您的数据包含真实文本,这会将标点符号与单词分开,并允许您正确匹配停用词。

关于python - 使用 NLTK 删除停用词时对象没有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53570495/

相关文章:

Python - 将 Visual Studio 项目转换为具有所有依赖项的 Docker 镜像

python - 下面的python代码有什么错误

python-3.x - wordnet python-nltk 接口(interface)是否包含任何语义相关性度量?

python - Eclipse 的 PyDev 插件

python - OpenCV:计算椭圆的长轴和短轴的方向角

python - TwilioRestClient 已删除

python - Dask:DataFrame 永远计算

python - pandas:四舍五入到用户定义的最接近的 float

python - 如何使用包含关键字对 Pandas 中的数据进行分类

NLTK 句子分词器不正确