1 回答

TA贡献1877条经验 获得超1个赞
您需要首先制作set停用词并使用列表理解来过滤标记。
def preprocessing(txt):
tokens = word_tokenize(txt)
# print(tokens)
stop_words = set(stopwords.words("english"))
tokens = [i for i in tokens if i not in stop_words]
return " ".join(tokens)
string = "Hey this is Sam. How are you?"
print(preprocessing(string))
输出:
'Hey Sam . How ?'
而不是使用for循环,使用df.apply如下:
df['text'] = df['text'].apply(preprocessing)
为什么集合优于列表
stopwords.words() 如果检查有重复条目,len(stopwords.words())并且len(set(stopwords.words())) 设置的长度小了几百。这就是为什么set这里是首选。
这是性能使用list和set
x = stopwords.words('english')
y = set(stopwords.words('english'))
%timeit new = [i for i in tokens if i not in x]
# 10000 loops, best of 3: 120 µs per loop
%timeit old = [j for j in tokens if j not in y]
# 1000000 loops, best of 3: 1.16 µs per loop
而且list-comprehension速度比平时快for-loop。
添加回答
举报