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循環(huán),使用df.apply如下:
df['text'] = df['text'].apply(preprocessing)
為什么集合優(yōu)于列表
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。
添加回答
舉報