【问题标题】:Stopword removal with pandas使用 pandas 去除停用词
【发布时间】:2019-01-25 14:57:41
【问题描述】:

我想从数据框的列中删除停用词。 列内有需要拆分的文本。

例如,我的数据框如下所示:

ID   Text
1    eat launch with me
2    go outside have fun

我想在text column 上应用停用词,所以它应该被拆分。

我试过这个:

for item in cached_stop_words:
    if item in df_from_each_file[['text']]:
        print(item)
        df_from_each_file['text'] = df_from_each_file['text'].replace(item, '')

所以我的输出应该是这样的:

ID   Text
1    eat launch 
2    go fun

这意味着停用词已被删除。 但它不能正常工作。我也尝试反之亦然,将我的数据框设为系列,然后循环遍历它,但我也没有工作。

感谢您的帮助。

【问题讨论】:

  • 您对此的预期输出是什么?
  • 感谢您的评论,我更新了问题:)

标签: python pandas dataframe text stop-words


【解决方案1】:

replace(单独)在这里不太适合,因为您想执行 部分 字符串替换。您想要基于正则表达式的替换。

当您的停用词数量可控时,一个简单的解决方案是使用str.replace

p = re.compile("({})".format('|'.join(map(re.escape, cached_stop_words))))
df['Text'] = df['Text'].str.lower().str.replace(p, '')

df
   ID               Text
0   1       eat launch  
1   2   outside have fun

如果性能很重要,请使用列表推导式。

cached_stop_words = set(cached_stop_words)
df['Text'] = [' '.join([w for w in x.lower().split() if w not in cached_stop_words]) 
    for x in df['Text'].tolist()]

df
   ID              Text
0   1        eat launch
1   2  outside have fun

【讨论】:

  • 非常感谢,它有效,除了你能不能也申请低一点。像 mg 和 MG 应该被同等对待
猜你喜欢
  • 1970-01-01
  • 2014-05-20
  • 2015-09-05
  • 2017-01-21
  • 2015-09-04
  • 2020-08-10
  • 2016-01-19
  • 1970-01-01
  • 2020-06-24
相关资源
最近更新 更多