Python基于詞頻排序實現(xiàn)快速挖掘關鍵詞
一、所有的代碼
這是所有的代碼
from collections import defaultdict
import jieba.posseg as jp
with open('keyword.txt','r',encoding='utf-8') as file:
keyword_list = file.read().split('\n')
not_flag = set(['w','x','y','z','un','m'])
not_word = set(['的','是','有','啊','呢','么','好'])
keyword_split = dict()
word_count = defaultdict(int)
for keyword in keyword_list:
word_set = set()
for word,flag in jp.cut(keyword):
if flag in not_flag:
continue
if word in not_word:
continue
if word == 'pdf' or word == 'PDF':
continue
word_count[word] += 1
word_set.add(word)
keyword_split[keyword] = word_set
id_keyword_list = defaultdict(list)
id_count = defaultdict(int)
for keyword,word_set in keyword_split.items():
word_sort = dict()
for word in word_set:
word_sort[word] = word_count[word]
word_sort = sorted(word_sort.items(),key=lambda x:x[1],reverse=True)
word_id = ','.join([word for word,count in word_sort[0:3]])
id_keyword_list[word_id] += [keyword]
id_count[word_id] += 1
result = []
id_count = sorted(id_count.items(),key=lambda x:x[1],reverse=True)
for word_id,count in id_count:
if count < 3:
continue
for keyword in id_keyword_list[word_id]:
result.append('%s\t%s' % (keyword,word_id))
result.append('')
with open('result.txt','wb') as file:
file.write('\n'.join(result).encode('utf-8'))
二、實現(xiàn)的效果
keyword.txt如下圖:
有50萬的關于pdf的關鍵詞數(shù)據(jù)

最后的輸出result.txt 就是將里面的含有關鍵詞相同的句子統(tǒng)一輸出出來:

這里會將一個句子的3個關鍵詞輸出出來 關鍵詞是根據(jù)詞頻排序的。
最后將所有關鍵詞一樣的句子組合在一起,就可以知道這些句子表達的意思大致一致
三、代碼解讀
keyword_list 是從keyword.txt讀取到的所有的句子
not_flag 是要排除的標記,不統(tǒng)計這些標記
not_word 是要排除的單詞,不統(tǒng)計這些單詞
keyword_split 是句子對應到他的所有單詞的字典,key是句子,value是他的所有單詞的集合

word_count 是所有的拆分后的單詞的次數(shù)的字典,key是單詞,value是單詞出現(xiàn)的次數(shù)

id_keyword_list 是一個字典,它的key是一個字符串 value是列表


id_count 是一個字典,它的key是一個字符串,value是int


最后對id_count處理 將結果輸出出來
id_count = sorted(id_count.items(), key=lambda x: x[1], reverse=True)
for word_id, count in id_count:
if count < 3:
continue
for keyword in id_keyword_list[word_id]:
result.append('%s\t%s' % (keyword, word_id))
result.append('')
到此這篇關于Python基于詞頻排序實現(xiàn)快速挖掘關鍵詞的文章就介紹到這了,更多相關Python挖掘關鍵詞內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
如何使用selenium和requests組合實現(xiàn)登錄頁面
這篇文章主要介紹了如何使用selenium和requests組合實現(xiàn)登錄頁面,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-02-02
使用Python3?Boto3包刪除AWS?CloudFormation的棧(Stacks)
這篇文章主要介紹了如何使用Python3?Boto3刪除AWS?CloudFormation的棧(Stacks),本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2024-01-01
Python實現(xiàn)對word文檔添加密碼去除密碼的示例代碼
這篇文章主要介紹了Python實現(xiàn)對word文檔添加密碼去除密碼,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12
Pyramid將models.py文件的內容分布到多個文件的方法
默認的Pyramid代碼結構中,就只有一個models.py文件,在實際項目中,如果需要對models進行分類,放到不同文件下,應該怎么辦2013-11-11
一文搞懂???????python可迭代對象,迭代器,生成器,協(xié)程
這篇文章主要介紹了一文搞懂???????python可迭代對象,迭代器,生成器,協(xié)程,微博吱嘎部分圍繞主題展開詳細介紹,需要的小伙伴可以參考一下2022-05-05
淺談Python中threading join和setDaemon用法及區(qū)別說明
這篇文章主要介紹了淺談Python中threading join和setDaemon用法及區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05

