Jieba provides two algorithms for keyword extraction via the jieba.analyse module.
TF-IDF Algorithm
jieba.analyse.extract_tags(sentence, topK=20, withWeight=False, allowPOS=())
topK: Number of keywords to return (default 20).withWeight: If True, returns weights along with keywords.allowPOS: Filter keywords by specific Part-of-Speech tags.
Customization:
jieba.analyse.set_idf_path(file_name): Set a custom IDF frequency corpus.jieba.analyse.set_stop_words(file_name): Set a custom stop words corpus.
jieba.analyse.textrank(sentence, topK=20, withWeight=False, allowPOS=('ns', 'n', 'vn', 'v'))
- Uses a graph-based approach (PageRank) on word co-occurrence within a sliding window.
- Note:
allowPOS has default filters for specific POS tags.
import jieba.analyse
text = "这是一个用于测试关键词提取的句子"
# TF-IDF
keywords = jieba.analyse.extract_tags(text, topK=5)
# TextRank
keywords_tr = jieba.analyse.textrank(text, topK=5)