python - 从文件中删除停用词

标签 python csv pandas

我想从我的文件的数据列中删除停用词。 我过滤掉了终端用户说话时的线路。 但它不会使用 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/

相关文章:

python - Panda 数据框中的百分比转换函数

python - 创建具有最大多样性的群组成员的群组

Python输出每个子目录下的文件个数到一个csv文件

python - 通过另一个 DataFrame 中的行将新列映射到 DataFrame

python - 如何使用 Python Pandas 在特定日期时间索引之后获取最近的单行

python - NumPy 广播 : Calculating sum of squared differences between two arrays

python - 打开 url 并检索更改的 url

Java hashmap 找不到现有条目

java - 当我尝试在 Spring 中下载 CSV 时获得 CPU 100%

python - 日内时间序列的多指数结构(10 分钟价格数据)