標籤:http io os ar strong for 資料 art sp
整理自 http://itindex.net/detail/44409-%E8%AE%A1%E7%AE%97-%E7%9B%B8%E4%BC%BC
說明:
* 其中基準資料,可以來自外部,處理過程為:
- 處理為詞袋
- 經過資料集的tfidf結果
* 無法處理中文
- 分詞器不支援
* 未另外載入語料庫
#!/usr/bin/env python#-*-coding=utf-8-*-"""未經處理資料"""#縮水版的courses,實際資料的格式應該為 課程名\t課程簡介\t課程詳情,並已去除html等幹擾因素courses = [‘Writing II: Rhetorical Composing‘, ‘Genetics and Society: A Course for Educators‘, ‘General Game Playing‘, ‘Genes and the Human Condition (From Behavior to Biotechnology)‘, ‘A Brief History of Humankind‘, ‘New Models of Business in Society‘, ‘Analyse Numrique pour Ingnieurs‘, ‘Evolution: A Course for Educators‘, ‘Coding the Matrix: Linear Algebra through Computer Science Applications‘, ‘The Dynamic Earth: A Course for Educators‘]#實際的 courses_name = [course.split(‘\t‘)[0] for course in courses]courses_name = [‘Writing II: Rhetorical Composing‘, ‘Genetics and Society: A Course for Educators‘, ‘General Game Playing‘, ‘Genes and the Human Condition (From Behavior to Biotechnology)‘, ‘A Brief History of Humankind‘, ‘New Models of Business in Society‘, ‘Analyse Numrique pour Ingnieurs‘, ‘Evolution: A Course for Educators‘, ‘Coding the Matrix: Linear Algebra through Computer Science Applications‘, ‘The Dynamic Earth: A Course for Educators‘]"""預先處理(easy_install nltk)"""#引入nltkimport nltk#nltk.download() #下載要用的語料庫等,時間比較長,最好提前準備好#分詞from nltk.corpus import browntexts_lower = [[word for word in document.lower().split()] for document in courses]from nltk.tokenize import word_tokenizetexts_tokenized = [[word.lower() for word in word_tokenize(document)] for document in courses]#去除停用詞from nltk.corpus import stopwordsenglish_stopwords = stopwords.words(‘english‘)texts_filtered_stopwords = [[word for word in document if not word in english_stopwords] for document in texts_tokenized]#去除標點符號english_punctuations = [‘,‘, ‘.‘, ‘:‘, ‘;‘, ‘?‘, ‘(‘, ‘)‘, ‘[‘, ‘]‘, ‘&‘, ‘!‘, ‘*‘, ‘@‘, ‘#‘, ‘$‘, ‘%‘]texts_filtered = [[word for word in document if not word in english_punctuations] for document in texts_filtered_stopwords]#詞幹化from nltk.stem.lancaster import LancasterStemmerst = LancasterStemmer()texts_stemmed = [[st.stem(word) for word in docment] for docment in texts_filtered]#去除過低頻詞all_stems = sum(texts_stemmed, [])stems_once = set(stem for stem in set(all_stems) if all_stems.count(stem) == 1)texts = [[stem for stem in text if stem not in stems_once] for text in texts_stemmed]"""注意:本例子中只用了course_name欄位,大多數word頻率過低,造成去除低頻詞後,有些document可能為空白 因此後面的處理結果只做示範""""""引入gensim,正式開始處理(easy_install gensim)輸入: 1.去掉了停用詞 2.去掉了標點符號 3.處理為詞幹 4.去掉了低頻詞"""from gensim import corpora, models, similarities#為了能看到過程日誌import logginglogging.basicConfig(format=‘%(asctime)s : %(levelname)s : %(message)s‘, level=logging.INFO)dictionary = corpora.Dictionary(texts)corpus = [dictionary.doc2bow(text) for text in texts] #doc2bow(): 將collection words 轉為詞袋,用兩元組(word_id, word_frequency)表示tfidf = models.TfidfModel(corpus)corpus_tfidf = tfidf[corpus]#拍腦袋的:訓練topic數量為10的LSI模型lsi = models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=10)index = similarities.MatrixSimilarity(lsi[corpus]) # index 是 gensim.similarities.docsim.MatrixSimilarity 執行個體"""對具體對象相似性匹配"""#選擇一個基準資料ml_course = texts[2]ml_bow = dictionary.doc2bow(ml_course) #在上面選擇的模型資料 lsi 中,計算其他資料與其的相似性ml_lsi = lsi[ml_bow] #ml_lsi 形式如 (topic_id, topic_value)sims = index[ml_lsi] #sims 是最終結果了, index[xxx] 調用內建方法 __getitem__() 來計算ml_lsi#排序,為輸出方便sort_sims = sorted(enumerate(sims), key=lambda item: -item[1])#查看結果print sort_sims[0:10] #看下前10個最相似的,第一個是基準資料自身print courses_name[2] #看下實際最相似的資料叫什麼
nltk-比較文檔相似性-完整執行個體