演算法介紹
1、讀取資料集中一篇或者多篇新聞作為分詞提取高頻詞彙的樣本資料集
2、對於文章首先用jieba庫中自帶的分詞函式對文章進行分詞處理
3、由於文章中的標點符號以及「的」, 「是」, 「了」 等常用詞無任何意義,因此這些詞是需要在進行統計高頻詞時進行刪除處理的,對於上述問題需要利用乙個停用字典(無意義詞的乙個文件集合)來過濾掉那些無意義的詞以及標點符號。
停用字典路徑:
**實現
import jieba
import glob
import random
class topkfrequent(object):
def __init__(self, k = 0):
self.k = k
def stop_words(self, path):
with open(path, 'r', encoding='utf8') as f:
return [l.strip() for l in f]
def get_content(self, path):
with open(path, 'r', encoding='gbk', errors='ignore') as f:
content = ''
for sample in f:
sample = sample.strip()
content += sample
return content
def get_tf(self, words):
tf_dic = {}
for word in words:
tf_dic[word] = tf_dic.get(word, 0) + 1
return sorted(tf_dic.items(), key=lambda x:x[1], reverse=true)[:self.k]
if __name__ == '__main__':
files = glob.glob(r'./learning-nlp-master/chapter-3/data/news/c000013/*.txt')
res = topkfrequent(10)
corpus = [res.get_content(x) for x in files]
random_index = random.randint(0, len(corpus))
split_words = [x for x in jieba.cut(corpus[random_index]) if x not in res.stop_words(r'./learning-nlp-master/chapter-3/data/stop_words.utf8')]
print(str(res.get_tf(split_words)))
自然語言處理 TF IDF演算法提取關鍵詞
這個標題看上去好像很複雜,其實我要談的是乙個很簡單的問題。這個問題涉及到資料探勘 文字處理 資訊檢索等很多計算機前沿領域,但是出乎意料的是,有乙個非常簡單的經典演算法,可以給出令人相當滿意的結果。它簡單到都不需要高等數學,普通人只用10分鐘就可以理解,這就是我今天想要介紹的tf idf演算法。乙個容...
自然語言處理 TF IDF演算法提取關鍵詞
這個標題看上去好像很複雜,其實我要談的是乙個很簡單的問題。這個問題涉及到資料探勘 文字處理 資訊檢索等很多計算機前沿領域,但是出乎意料的是,有乙個非常簡單的經典演算法,可以給出令人相當滿意的結果。它簡單到都不需要高等數學,普通人只用10分鐘就可以理解,這就是我今天想要介紹的tf idf演算法。乙個容...
自然語言處理之關鍵詞提取TF IDF
1 公式 計算詞頻tf 考慮到文章有長短之分,為了便於不同文章的比較,進行 詞頻 標準化。或者 計算反文件頻率idf import osimport math import operator filepath h data allfiles allfiles doc word dict i 0 統計...