当前位置:   article > 正文

nltk-比较中文文档相似度-完整实例_nltk 中文语义相识度

nltk 中文语义相识度

nltk同时也能处理中文的场景,只要做如下改动:

  1. 使用中文分词器(如我选用了结巴分词)

  2. 对中文字符做编码处理,使用unicode编码方式

  3. python的源码编码统一声明为 gbk

  4. 使用支持中文的语料库


代码如下,需要jieba的支持

  1. #!/usr/bin/env python
  2. #-*-coding=gbk-*-
  3. """
  4. 原始数据,用于建立模型
  5. """
  6. #缩水版的courses,实际数据的格式应该为 课程名\t课程简介\t课程详情,并已去除html等干扰因素
  7. courses = [
  8. u'Writing II: Rhetorical Composing',
  9. u'Genetics and Society: A Course for Educators',
  10. u'General Game Playing',
  11. u'Genes and the Human Condition (From Behavior to Biotechnology)',
  12. u'A Brief History of Humankind',
  13. u'New Models of Business in Society',
  14. u'Analyse Numrique pour Ingnieurs',
  15. u'Evolution: A Course for Educators',
  16. u'Coding the Matrix: Linear Algebra through Computer Science Applications',
  17. u'The Dynamic Earth: A Course for Educators',
  18. u'Tiny Wings\tYou have always dreamed of flying - but your wings are tiny. Luckily the world is full of beautiful hills. Use the hills as jumps - slide down, flap your wings and fly! At least for a moment - until this annoying gravity brings you back down to earth. But the next hill is waiting for you already. Watch out for the night and fly as fast as you can. ',
  19. u'Angry Birds Free',
  20. u'没有\它很相似',
  21. u'没有\t它很相似',
  22. u'没有\t他很相似',
  23. u'没有\t他不很相似',
  24. u'没有',
  25. u'可以没有',
  26. u'也没有',
  27. u'有没有也不管',
  28. u'Angry Birds Stella',
  29. u'Flappy Wings - FREE\tFly into freedom!A parody of the #1 smash hit game!',
  30. u'没有一个',
  31. u'没有一个2',
  32. ]
  33. #只是为了最后的查看方便
  34. #实际的 courses_name = [course.split('\t')[0] for course in courses]
  35. courses_name = courses
  36. """
  37. 预处理(easy_install nltk)
  38. """
  39. def pre_process_cn(courses, low_freq_filter = True):
  40. """
  41. 简化的 中文+英文 预处理
  42. 1.去掉停用词
  43. 2.去掉标点符号
  44. 3.处理为词干
  45. 4.去掉低频词
  46. """
  47. import nltk
  48. import jieba.analyse
  49. from nltk.tokenize import word_tokenize
  50. texts_tokenized = []
  51. for document in courses:
  52. texts_tokenized_tmp = []
  53. for word in word_tokenize(document):
  54. texts_tokenized_tmp += jieba.analyse.extract_tags(word,10)
  55. texts_tokenized.append(texts_tokenized_tmp)
  56. texts_filtered_stopwords = texts_tokenized
  57. #去除标点符号
  58. english_punctuations = [',', '.', ':', ';', '?', '(', ')', '[', ']', '&', '!', '*', '@', '#', '$', '%']
  59. texts_filtered = [[word for word in document if not word in english_punctuations] for document in texts_filtered_stopwords]
  60. #词干化
  61. from nltk.stem.lancaster import LancasterStemmer
  62. st = LancasterStemmer()
  63. texts_stemmed = [[st.stem(word) for word in docment] for docment in texts_filtered]
  64. #去除过低频词
  65. if low_freq_filter:
  66. all_stems = sum(texts_stemmed, [])
  67. stems_once = set(stem for stem in set(all_stems) if all_stems.count(stem) == 1)
  68. texts = [[stem for stem in text if stem not in stems_once] for text in texts_stemmed]
  69. else:
  70. texts = texts_stemmed
  71. return texts
  72. lib_texts = pre_process_cn(courses)
  73. """
  74. 引入gensim,正式开始处理(easy_install gensim)
  75. """
  76. def train_by_lsi(lib_texts):
  77. """
  78. 通过LSI模型的训练
  79. """
  80. from gensim import corpora, models, similarities
  81. #为了能看到过程日志
  82. #import logging
  83. #logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
  84. dictionary = corpora.Dictionary(lib_texts)
  85. corpus = [dictionary.doc2bow(text) for text in lib_texts] #doc2bow(): 将collection words 转为词袋,用两元组(word_id, word_frequency)表示
  86. tfidf = models.TfidfModel(corpus)
  87. corpus_tfidf = tfidf[corpus]
  88. #拍脑袋的:训练topic数量为10的LSI模型
  89. lsi = models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=10)
  90. index = similarities.MatrixSimilarity(lsi[corpus]) # index 是 gensim.similarities.docsim.MatrixSimilarity 实例
  91. return (index, dictionary, lsi)
  92. #库建立完成 -- 这部分可能数据很大,可以预先处理好,存储起来
  93. (index,dictionary,lsi) = train_by_lsi(lib_texts)
  94. #要处理的对象登场
  95. target_courses = [u'没有']
  96. target_text = pre_process_cn(target_courses, low_freq_filter=False)
  97. """
  98. 对具体对象相似度匹配
  99. """
  100. #选择一个基准数据
  101. ml_course = target_text[0]
  102. #词袋处理
  103. ml_bow = dictionary.doc2bow(ml_course)
  104. #在上面选择的模型数据 lsi 中,计算其他数据与其的相似度
  105. ml_lsi = lsi[ml_bow] #ml_lsi 形式如 (topic_id, topic_value)
  106. sims = index[ml_lsi] #sims 是最终结果了, index[xxx] 调用内置方法 __getitem__() 来计算ml_lsi
  107. #排序,为输出方便
  108. sort_sims = sorted(enumerate(sims), key=lambda item: -item[1])
  109. #查看结果
  110. print sort_sims[0:10] #看下前10个最相似的,第一个是基准数据自身
  111. print courses_name[sort_sims[1][0]] #看下实际最相似的数据叫什么
  112. print courses_name[sort_sims[2][0]] #看下实际最相似的数据叫什么
  113. print courses_name[sort_sims[3][0]] #看下实际最相似的数据叫什么



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/542976
推荐阅读
  

闽ICP备14008679号