我想从我的文件的数据列中删除停用词。
我过滤掉了终端用户说话时的线路。
但它不会使用 usertext.apply(lambda x: [word for word in x if word not in stop_words])
过滤掉停用词
我究竟做错了什么?
import pandas as pd
from stop_words import get_stop_words
df = pd.read_csv("F:/textclustering/data/cleandata.csv", encoding="iso-8859-1")
usertext = df[df.Role.str.contains("End-user",na=False)][['Data','chatid']]
stop_words = get_stop_words('dutch')
clean = usertext.apply(lambda x: [word for word in x if word not in stop_words])
print(clean)
最佳答案
您可以构建停用词的正则表达式模式并调用矢量化的 str.replace
来删除它们:
In [124]:
stop_words = ['a','not','the']
stop_words_pat = '|'.join(['\\b' + stop + '\\b' for stop in stop_words])
stop_words_pat
Out[124]:
'\\ba\\b|\\bnot\\b|\\bthe\\b'
In [125]:
df = pd.DataFrame({'text':['a to the b', 'the knot ace a']})
df['text'].str.replace(stop_words_pat, '')
Out[125]:
0 to b
1 knot ace
Name: text, dtype: object
在这里,我们执行列表推导式,用 '\b'
围绕每个停用词构建一个模式,这是一个中断,然后我们使用 or
所有单词'|'
关于python - 从文件中删除停用词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42674113/