鱼C论坛

 找回密码
 立即注册
查看: 2125|回复: 8

lda分析 用jieba分词但是做不出来,报错了,求助

[复制链接]
发表于 2022-2-12 21:09:21 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
报错,找不到原因
File "D:\python370\lib\site-packages\jieba\_compat.py", line 79, in strdecode
    sentence = sentence.decode('utf-8')
AttributeError: 'int' object has no attribute 'decode'
  1. """
  2. ---------------------------------
  3. test: rzbbzr
  4. test1: PyCharm
  5. test2: LDA20220212.py
  6. test3: 2022-02-12 11:38
  7. Pyinstaller -F  LDA20220212.py
  8. py转jupyter %load xxxx.py
  9. pip install -i https://pypi.doubanio.com/simple/ 包名
  10. pip install -i https://pypi.tuna.tsinghua.edu.cn/simple +包名
  11. """
  12. import os
  13. import pandas as pd
  14. import re
  15. import jieba
  16. import jieba.posseg as psg

  17. #######预处理

  18. output_path = 'D:/lda/data/result'
  19. file_path = 'D:/lda/data'
  20. os.chdir(file_path)
  21. data = pd.read_excel("D:/lda/data/data.xlsx")
  22. os.chdir(output_path)
  23. dic_file = "D:/lda/data/dict.txt"
  24. stop_file = "D:/lda/data/stopwords.txt"


  25. def chinese_word_cut(mytext):
  26.     jieba.load_userdict(dic_file)
  27.     jieba.initialize()
  28.     try:
  29.         stopword_list = open(stop_file, encoding='utf-8')
  30.     except:
  31.         stopword_list = []
  32.         print("error in stop_file")
  33.     stop_list = []
  34.     flag_list = ['n', 'nz', 'vn']
  35.     for line in stopword_list:
  36.         line = re.sub(u'\n|\\r', '', line)
  37.         stop_list.append(line)

  38.     word_list = []
  39.     # jieba分词
  40.     seg_list = psg.cut(mytext)
  41.     for seg_word in seg_list:
  42.         # word = re.sub(u'[^\u4e00-\u9fa5]','',seg_word.word)
  43.         # seg_word = str(seg_word).strip()
  44.         print(type(seg_word))
  45.         word = seg_word.word


  46.         find = 0
  47.         print(type(word))
  48.         for stop_word in stop_list:


  49.             if stop_word == word or len(word) < 2:  # this word is stopword
  50.                 find = 1

  51.                 break
  52.         if find == 0 and seg_word.flag in flag_list:
  53.             word_list.append(word)
  54.     return (" ").join(word_list)


  55. data["content_cutted"] = data.content.apply(chinese_word_cut)

  56. #######LDA分析

  57. from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
  58. from sklearn.decomposition import LatentDirichletAllocation


  59. def print_top_words(model, feature_names, n_top_words):
  60.     tword = []
  61.     for topic_idx, topic in enumerate(model.components_):
  62.         print("Topic #%d:" % topic_idx)
  63.         topic_w = " ".join([feature_names[i] for i in topic.argsort()[:-n_top_words - 1:-1]])
  64.         tword.append(topic_w)
  65.         print(topic_w)
  66.     return tword


  67. n_features = 1000  # 提取1000个特征词语
  68. tf_vectorizer = CountVectorizer(strip_accents='unicode',
  69.                                 max_features=n_features,
  70.                                 stop_words='english',
  71.                                 max_df=0.5,
  72.                                 min_df=10)
  73. tf = tf_vectorizer.fit_transform(data.content_cutted)

  74. n_topics = 8
  75. lda = LatentDirichletAllocation(n_components=n_topics, max_iter=50,
  76.                                 learning_method='batch',
  77.                                 learning_offset=50,
  78.                                 #                                 doc_topic_prior=0.1,
  79.                                 #                                 topic_word_prior=0.01,
  80.                                 random_state=0)
  81. lda.fit(tf)

  82. ###########每个主题对应词语
  83. n_top_words = 25
  84. tf_feature_names = tf_vectorizer.get_feature_names()
  85. topic_word = print_top_words(lda, tf_feature_names, n_top_words)

  86. ###########输出每篇文章对应主题
  87. import numpy as np

  88. topics = lda.transform(tf)
  89. topic = []
  90. for t in topics:
  91.     topic.append(list(t).index(np.max(t)))
  92. data['topic'] = topic
  93. data.to_excel("data_topic.xlsx", index=False)
  94. topics[0]  # 0 1 2

  95. ###########可视化

  96. import pyLDAvis
  97. import pyLDAvis.sklearn

  98. pyLDAvis.enable_notebook()
  99. pic = pyLDAvis.sklearn.prepare(lda, tf, tf_vectorizer)
  100. pyLDAvis.display(pic)
  101. pyLDAvis.save_html(pic, 'lda_pass' + str(n_topics) + '.html')
  102. # 去工作路径下找保存好的html文件
  103. # pyLDAvis.show(pic)


  104. ###########困惑度
  105. import matplotlib.pyplot as plt

  106. plexs = []
  107. n_max_topics = 16
  108. for i in range(1, n_max_topics):
  109.     print(i)
  110.     lda = LatentDirichletAllocation(n_components=i, max_iter=50,
  111.                                     learning_method='batch',
  112.                                     learning_offset=50, random_state=0)
  113.     lda.fit(tf)
  114.     plexs.append(lda.perplexity(tf))

  115. n_t = 15  # 区间最右侧的值。注意:不能大于n_max_topics
  116. x = list(range(1, n_t))
  117. plt.plot(x, plexs[1:n_t])
  118. plt.xlabel("number of topics")
  119. plt.ylabel("perplexity")
  120. plt.show()


  121. 用的下面的数据

  122. 链接:https://pan.baidu.com/s/1OkzDW_fXarDOGQg3VOYb3w
  123. 提取码:1111

  124. 问题出在jieba那里 , 谢谢
















复制代码

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2022-2-12 21:41:28 | 显示全部楼层
报错贴全一点,把完整的回溯过程贴上来
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-2-12 21:52:50 | 显示全部楼层
isdkz 发表于 2022-2-12 21:41
报错贴全一点,把完整的回溯过程贴上来
  1. Traceback (most recent call last):
  2.   File "C:/Users/Administrator/PycharmProjects/pythonProject2/venv/lda/LDA20220212.py", line 67, in <module>
  3.     data["content_cutted"] = data.content.apply(chinese_word_cut)
  4.   File "D:\python370\lib\site-packages\pandas\core\series.py", line 4213, in apply
  5.     mapped = lib.map_infer(values, f, convert=convert_dtype)
  6.   File "pandas\_libs\lib.pyx", line 2403, in pandas._libs.lib.map_infer
  7.   File "C:/Users/Administrator/PycharmProjects/pythonProject2/venv/lda/LDA20220212.py", line 46, in chinese_word_cut
  8.     for seg_word in seg_list:
  9.   File "D:\python370\lib\site-packages\jieba\posseg\__init__.py", line 294, in cut
  10.     for w in dt.cut(sentence, HMM=HMM):
  11.   File "D:\python370\lib\site-packages\jieba\posseg\__init__.py", line 249, in cut
  12.     for w in self.__cut_internal(sentence, HMM=HMM):
  13.   File "D:\python370\lib\site-packages\jieba\posseg\__init__.py", line 217, in __cut_internal
  14.     sentence = strdecode(sentence)
  15.   File "D:\python370\lib\site-packages\jieba\_compat.py", line 79, in strdecode
  16.     sentence = sentence.decode('utf-8')
  17. AttributeError: 'int' object has no attribute 'decode'
复制代码

就上面这些,不知道应该改哪里
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-2-12 22:10:52 | 显示全部楼层
本帖最后由 isdkz 于 2022-2-12 22:41 编辑

在第67行前面加上这句试试
  1. data.fillna('', inplace=True)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-2-12 22:15:52 | 显示全部楼层
  1. data["content_cutted"] = data.content.apply(chinese_word_cut)
复制代码


这里错了,整形没有decode方法。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-2-12 22:50:21 | 显示全部楼层
isdkz 发表于 2022-2-12 22:10
在第67行前面加上这句试试

没起作用,还是报那个错误
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-2-12 22:52:17 | 显示全部楼层
swanseabrian 发表于 2022-2-12 22:50
没起作用,还是报那个错误

好吧
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-2-13 09:39:46 | 显示全部楼层
z5560636 发表于 2022-2-12 22:15
这里错了,整形没有decode方法。

那这里要怎么改一下,我不会改还,谢谢
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-2-13 11:35:49 | 显示全部楼层
方便把另外两个文件放上来吗?不然不好帮你调试
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-30 09:56

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表