【问题标题】:NLP - Removing Stop Words and Counting Word FrequencyNLP - 去除停用词并计算词频
【发布时间】:2020-06-24 15:34:44
【问题描述】:

我目前有一个工作脚本,可以对来自我们数据库的数据列 (conversation_message__body) 的词频进行简单计数。工作代码示例和输出(图像)如下。

import pandas as pd
import numpy as np

x = df.conversation_message__body.str.split(expand=True).stack().value_counts()

y = pd.DataFrame(data=x)

y.reset_index(level=0,inplace=True)

print(y)

问题是我想从这个分析中排除很多词。据我了解,这是 NLP 中的一个常见问题。所以我修改了我的脚本,如下所示:

# Import stopwords with nltk.
from nltk.corpus import stopwords
import pandas as pd
import numpy as np

stop = stopwords.words('english')
newStopWords = ['hello','hi','hey','im','get']
stop.extend(newStopWords)

df['conversation_message__body'] = df.conversation_message__body.str.replace("[^\w\s]", "").str.lower()

df['conversation_message__body'] = df['conversation_message__body'].apply(lambda x: [item for item in x.split() if item not in stop])

x = df.conversation_message__body.str.split(expand=True).stack().value_counts()

y = pd.DataFrame(data=x)

y.reset_index(level=0,inplace=True)

print(y)

为我工作并且不返回任何结果。即使我尝试print(x) 看看最初的转换是什么样子,我也只能返回>Series([], dtype: int64)

我很确定这里缺少一些基础知识,但是我已经为此工作了一段时间,但没有运气。谁能把我推向正确的方向?

【问题讨论】:

  • 你能创建一个minimal reproducible example 吗?
  • 我猜这很难,因为我无法在此处提供输入。输入是 1 列和多行,每个单元格都是包含对话注释的长格式文本字段。我显然没有尽可能多地了解 MRE,但是第二个代码块是我想要开始工作的。

标签: python-3.x pandas dataframe nlp stop-words


【解决方案1】:

您的列中需要str,而不是单词列表。

小例子:

df = pd.DataFrame({ 'conv': 
                   ["hi im Jon. I am reaching out to schedule a meeting on Monday.", "That wouldn't be possible as I am out."]})

数据如下:

    conv
0   jon reaching schedule meeting monday
1   wouldnt possible

然后:

df['conv'] = df['conv'].str.replace("[^\w\s]", "").str.lower()

现在你需要在conv 中有字符串,你的代码给出了字符串列表。

df['conv'] = df['conv'].apply(lambda x: ' '.join([item for item in x.split() if item not in stop]))
df['conv'].str.split(expand=True).stack().value_counts()

输出:

wouldnt     1
jon         1
possible    1
meeting     1
reaching    1
monday      1
schedule    1
dtype: int64

【讨论】:

    猜你喜欢
    • 2018-04-02
    • 2021-11-30
    • 2022-07-22
    • 2018-10-22
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    • 2021-02-28
    • 2011-02-22
    相关资源
    最近更新 更多