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

时间:2018-12-01 11:53:07

标签: python pandas nltk

我正试图从熊猫数据框架中从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'

1 个答案:

答案 0 :(得分:2)

听起来像您的文本中有一些数字,它们使熊猫变得有点聪明。将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)。如果您的数据包含真实文本,则会将标点符号与单词分开,并允许您正确匹配停用词。