【问题标题】:Python - From list of list of tokens to bag of wordsPython - 从标记列表列表到词袋
【发布时间】:2018-07-06 13:34:22
【问题描述】:

我正在努力计算词袋。我有一个带有文本列的 pandas 数据框,我正确地对其进行标记、删除停用词和词干。 最后,对于每个文档,我都有一个字符串列表。

我的最终目标是为本专栏计算词袋,我已经看到 scikit-learn 有一个功能可以做到这一点,但它适用于字符串,而不是字符串列表。

我正在使用 NLTK 自己进行预处理,并希望保持这种状态...

有没有办法根据标记列表计算词袋?例如,类似的东西:

["hello", "world"]
["hello", "stackoverflow", "hello"]

应该转换成

[1, 1, 0]
[2, 0, 1]

用词汇:

["hello", "world", "stackoverflow"]

【问题讨论】:

标签: python pandas scikit-learn nlp nltk


【解决方案1】:

使用 sklearn.feature_extraction.text.CountVectorizer

import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer

df = pd.DataFrame({'text': [['hello', 'world'], 
                        ['hello', 'stackoverflow', 'hello']]
                   })

## Join words to a single line as required by CountVectorizer
df['text'] = df['text'].apply(lambda x: ' '.join([word for word in x]))

vectorizer = CountVectorizer(lowercase=False)
x = vectorizer.fit_transform(df['text'].values)

print(vectorizer.get_feature_names())
print(x.toarray())

输出:

['hello', 'stackoverflow', 'world']

[[1 0 1]
 [2 1 0]]

【讨论】:

    【解决方案2】:

    sklearn.feature_extraction.text.CountVectorizer 可以提供很多帮助。以下是官方文档的示例:

    from sklearn.feature_extraction.text import CountVectorizer
    vectorizer = CountVectorizer()
    corpus = [
        'This is the first document.',
        'This is the second second document.',
        'And the third one.',
        'Is this the first document?',
    ]
    X = vectorizer.fit_transform(corpus)
    X.toarray() 
    /*array([[0, 1, 1, 1, 0, 0, 1, 0, 1],
       [0, 1, 0, 1, 0, 2, 1, 0, 1],
       [1, 0, 0, 0, 1, 0, 1, 1, 0],
       [0, 1, 1, 1, 0, 0, 1, 0, 1]]...)*/
    

    您可以使用方法vectorizer.get_feature_names() 获取特征名称。

    【讨论】:

      【解决方案3】:

      您可以通过使用Counter 过滤创建DataFrame,然后转换为lists:

      from collections import Counter
      
      df = pd.DataFrame({'text':[["hello", "world"],
                                 ["hello", "stackoverflow", "hello"]]})
      
      L = ["hello", "world", "stackoverflow"]
      
      f = lambda x: Counter([y for y in x if y in L])
      df['new'] = (pd.DataFrame(df['text'].apply(f).values.tolist())
                     .fillna(0)
                     .astype(int)
                     .reindex(columns=L)
                     .values
                     .tolist())
      print (df)
      
                                  text        new
      0                 [hello, world]  [1, 1, 0]
      1  [hello, stackoverflow, hello]  [2, 0, 1]
      

      【讨论】:

        猜你喜欢
        • 2014-02-17
        • 1970-01-01
        • 2019-10-04
        • 2019-10-31
        • 2019-03-15
        • 1970-01-01
        • 1970-01-01
        • 2019-08-07
        相关资源
        最近更新 更多