以下是一份示例代码,需要使用第三方库jieba、wordcloud和matplotlib:

import jieba
import jieba.posseg as pseg
from wordcloud import WordCloud
import matplotlib.pyplot as plt

# 读取文件
with open('text.txt', 'r', encoding='utf-8') as f:
    text = f.read()

# 分词和词性标注
words = pseg.cut(text)
# 筛选名词
nouns = []
for word, flag in words:
    if flag.startswith('n'):
        nouns.append(word)

# 去除停用词和标点符号
with open('stopwords.txt', 'r', encoding='utf-8') as f:
    stopwords = f.read().split()
nouns = [word for word in nouns if word not in stopwords and word != ' ' and word != '\n']

# 统计词频并排序
freq = {}
for noun in nouns:
    freq[noun] = freq.get(noun, 0) + 1
freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)

# 输出前十个关键词
for i in range(10):
    print(freq[i])

# 生成词云图
wc = WordCloud(font_path='simhei.ttf', background_color='white', width=800, height=400, max_words=100, shape='rectangle')
wc.generate_from_frequencies(freq[:10])
plt.imshow(wc)
plt.axis('off')
plt.show()

其中,停用词表stopwords.txt可以自行准备,也可以使用哈工大停用词表。在生成词云图时,设置了词云图的形状为长方形,可以根据实际需要进行调整

使用python编写代码要求对txt文件中的中文文本进行关键词提取并对关键词进行词性筛选筛选出名词后使用哈工大停用词表去除停用词和标点符号然后统计关键词的出现频次并排序输出出现频次前十的关键词最后绘制出这十个词的词云图词云图形状为长方形

原文地址: https://www.cveoy.top/t/topic/e9WP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录