社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何在python中生成词频矩阵

Hafiz Siddiq • 7 年前 • 3212 次点击  

我正在研究一个情绪分析问题,我必须准备一个文档频率矩阵。例如,我有三个词(数据)与情绪

他是个好人

他是个坏学生

他工作努力,积极向上

在这个独特的词汇表中有下列单词。

他,是,A,好,人,坏,学生,勤奋

根据词汇和数据,我将有3x8矩阵如下

第一句话:1,1,1,1,1,0,0,0

第二句:1,1,0,0,0,1,1,0

第三句:1,1,0,0,0,0,0,1

请提出用python实现这一点的最佳和有效的方法。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/43363
文章 [ 2 ]  |  最新文章 7 年前
Daniel Mesejo
Reply   •   1 楼
Daniel Mesejo    7 年前

因为你用 machine-learning ,我建议您使用 sklearn.CountVectorizer :

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

corpus = ['He is a good person',
          'He is bad student',
          'He is hardworking']
df = pd.DataFrame(data=corpus, columns=['sentences'])

vectorizer = CountVectorizer(vocabulary=['he', 'is', 'a', 'good', 'person', 'bad', 'student', 'hardworking'], min_df=0,
                             stop_words=frozenset(), token_pattern=r"(?u)\b\w+\b")
X = vectorizer.fit_transform(df['sentences'].values)
result = pd.DataFrame(data=X.toarray(), columns=vectorizer.get_feature_names())
print(result)

产量

   he  is  a  good  person  bad  student  hardworking
0   1   1  1     1       1    0        0            0
1   1   1  0     0       0    1        1            0
2   1   1  0     0       0    0        0            1
WeNYoBen
Reply   •   2 楼
WeNYoBen    7 年前

这是 get_dummies 问题,为了达到你所需要的,你只需要跟随 reindex

s='He,is,a,good,person,bad,student,hardworking'.split(',')
df.W1.str.get_dummies(sep=' ').reindex(columns=s)
Out[914]: 
   He  is  a  good  person  bad  student  hardworking
0   1   1  1     1       1    0        0            0
1   1   1  0     0       0    1        1            0
2   1   1  0     0       0    0        0            1

数据输入

                    W1               W2
0  He is a good person     Positive Sense
1  He is bad student       Negative Sense
2  He is hardworking       Positive Sense