我正在尝试从 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/