Tahm 2021-06-03 02:19 采纳率: 100%
浏览 259
已采纳

请问停用词过滤txt没起作用怎么办?

以下是我的代码:

import jieba
import os
import warnings
warnings.filterwarnings('ignore')  
from gensim.corpora.dictionary import Dictionary
from gensim.models.ldamodel import LdaModel
from wordcloud import WordCloud
import matplotlib.pyplot as plt

textfile=input("输入文本文件名:")
num_topics=int(input("话题数:"))
f=open(textfile, "r",encoding="utf-8")
lines=f.readlines()
f.close()

stoplist=open(r'C:\Users\26552\Desktop\stopword.txt','r',encoding="utf-8").read()
stoplist = set(w.strip() for w in stoplist)

segtexts=[]
for line in lines:
    doc=[]
    for w in list(jieba.cut(line,cut_all=True)):
        if len(w)>1 and w not in stoplist:
            doc.append(w)
    segtexts.append(doc)
dictionary = Dictionary(segtexts)
dictionary.filter_extremes(2,1.0,keep_n=1000)
corpus = [dictionary.doc2bow(text) for text in segtexts]
lda = LdaModel(corpus,id2word=dictionary, num_topics=num_topics)
topics=lda.print_topics(num_topics=num_topics,num_words=10)
print(topics)

font = r'C:\Users\26552\Desktop\simfang.ttf'
wc=WordCloud(collocations=False, font_path=font, width=2800, height=2800, max_words=20,margin=2)
for topicid in range(0,num_topics):
    tlist=lda.get_topic_terms(topicid, topn=20)
    
    wdict={} 
    for wv in tlist:
        wdict[ dictionary[wv[0]]]=wv[1]
    print(wdict)
    wordcloud = wc.generate_from_frequencies(wdict)
    wordcloud.to_file('topic_'+str(topicid)+'.png')  

这是停用词文本文档:

路径没有问题,请问老哥们,是我的代码哪里出问题了吗?

如能指正,不胜感激!

  • 写回答

3条回答 默认 最新

  • CSDN专家-HGJ 2021-06-03 02:59
    关注

    问题出在这行stoplist = set(w.strip() for w in stoplist),stoplist是从文件中读取出来的字符串,不是列表,遍历取出的是单个字符,不是停用词,所以后面停用词过滤失效。这样改一下就行了:

    stoplist = set(w for w in stoplist.split('\n'))#对停用词文本按行分割成列表,每个元素就是停用词
    #或者直接用列表更简洁:
    stoplist = [w for w in stoplist.split('\n')]

    如对解答满意,请点击采纳一下。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。