语义的特征提取及简单词频展示(WordCloud)

版权声明:未经本人同意不得转载! https://blog.csdn.net/yanpenggong/article/details/84704901

对于语句分析,以及词云展示,具体代码如下:

# coding=utf-8
import jieba
import numpy
import pandas as pd
from wordcloud import WordCloud
import matplotlib.pyplot as plt

# 将三个句子用jieba.cut处理
content1 = jieba.lcut("今天很残酷,明天更残酷,后天很美好,但绝对大部分是死在明天晚上,所以每个人不要放弃今天。")
content2 = jieba.lcut("我们看到的从很远星系来的光是在几百万年之前发出的,这样当我们看到宇宙时,我们是在看它的过去。")
content3 = jieba.lcut("如果只用一种方式了解某样事物,你就不会真正了解它。了解事物真正含义的秘密取决于如何将其与我们所了解的事物相联系。")

# 将此三个转换成列表
content1 = ' '.join(list(content1))
content2 = ' '.join(list(content2))
content3 = ' '.join(list(content3))

# 实例化count
count = CountVectorizer(stop_words=["不会", "如果"])

# 对三篇文章进行特征提取
data = count.fit_transform([content1, content2, content3])

# 内容打印
print(count.get_feature_names())
print(data.toarray())

# 云词展示
# 统计云词
words = [content1.split(" "), content2.split(" "), content3.split(" ")]
stopwords = ["不会", "如果","师兄",  ",", "。"]
all_words = []
for word in words:
    for i in word:
        if i in stopwords or len(i)==1:
            continue
        all_words.append(str(i))

# 转为DataFrame形式
all_words = pd.DataFrame({"all_words": all_words})

words_count = all_words.groupby(by=["all_words"])["all_words"].agg({"count": numpy.size})
words_count = words_count.reset_index().sort_values(by=["count"], ascending=False)

wordcloud = WordCloud(font_path="/Library/Fonts/Songti.ttc", background_color="white", max_font_size=80)
word_frequence = {x[0]: x[1] for x in words_count.head(len(words_count)-1).values}
wordcloud = wordcloud.fit_words(word_frequence)

# 词频展示
plt.imshow(wordcloud)

输出:

['一种', '不要', '之前', '了解', '事物', '今天', '光是在', '几百万年', '发出', '取决于', '只用', '后天', '含义', '大部分', '如何', '宇宙', '我们', '所以', '放弃', '方式', '明天', '星系', '晚上', '某样', '残酷', '每个', '看到', '真正', '秘密', '绝对', '美好', '联系', '过去', '这样']
[[0 1 0 0 0 2 0 0 0 0 0 1 0 1 0 0 0 1 1 0 2 0 1 0 2 1 0 0 0 1 1 0 0 0]
 [0 0 1 0 0 0 1 1 1 0 0 0 0 0 0 1 3 0 0 0 0 1 0 0 0 0 2 0 0 0 0 0 1 1]
 [1 0 0 4 3 0 0 0 0 1 1 0 1 0 1 0 1 0 0 1 0 0 0 1 0 0 0 2 1 0 0 1 0 0]]

生成的图像为:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/yanpenggong/article/details/84704901