首页 > 解决方案 > 如何找到类别中的唯一单词 - Python

问题描述

我有一个数据框,其中 column1 包含文本数据,column2 包含文本的类别,包含在 column1 中。我想找到一个类别(即非正式)的文本数据中出现的单词,但不会出现在其他类别中。数据框中的多行将具有相同的类别。

        Textual                           Category 
Hi johnny how are you today              Informal 
Dear Johnny                              Formal
Hey Johnny                               Informal
To Johnny                                Formal

示例输出:

Informal: [Hi, how, are, you, today, Hey]
Formal: [Dear, To]

标签: pythonpandasnltk

解决方案


# Remove punctuation
df.Textual = df.Textual.str.replace('.', '')
df.Textual = df.Textual.str.replace(',', '')
df.Textual = df.Textual.str.replace('?', '')

# get list of all words per Category
df1 = df.groupby(['Category'])['Textual'].apply(' '.join).reset_index()
df1['Textual'] = df1.Textual.str.split().apply(lambda x: list(filter(None, list(set(x)))))
print(df1)

# Split the list in different columns
df = pd.DataFrame(df1.Textual.values.tolist(), index= df1.index)
print(df)

# Reshape the df to have a line for each word
df['Category'] = df1.Category
df = df.set_index("Category")
df = df.stack()
print(df)

# Drop word that are present in several Categories
df = df.str.upper().drop_duplicates(keep=False)
print(df)

# Reshape the df to the expected output
df = df.groupby('Category').apply(list)
print(df)

推荐阅读