Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add parameter logTF in extract_tags to determine whether to weight TF #1023

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions jieba/analyse/tfidf.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# encoding=utf-8
from __future__ import absolute_import

import math
import os
import jieba
import jieba.posseg
Expand Down Expand Up @@ -72,7 +74,7 @@ def set_idf_path(self, idf_path):
self.idf_loader.set_new_path(new_abs_path)
self.idf_freq, self.median_idf = self.idf_loader.get_idf()

def extract_tags(self, sentence, topK=20, withWeight=False, allowPOS=(), withFlag=False):
def extract_tags(self, sentence, topK=20, withWeight=False, allowPOS=(), withFlag=False, logTF=False):
"""
Extract keywords from sentence using TF-IDF algorithm.
Parameter:
Expand All @@ -84,6 +86,8 @@ def extract_tags(self, sentence, topK=20, withWeight=False, allowPOS=(), withFla
- withFlag: only work with allowPOS is not empty.
if True, return a list of pair(word, weight) like posseg.cut
if False, return a list of words
- logTF: if True, use log2(TF) to weigh the word frequency
if False, use raw TF
"""
if allowPOS:
allowPOS = frozenset(allowPOS)
Expand All @@ -104,7 +108,10 @@ def extract_tags(self, sentence, topK=20, withWeight=False, allowPOS=(), withFla
total = sum(freq.values())
for k in freq:
kw = k.word if allowPOS and withFlag else k
freq[k] *= self.idf_freq.get(kw, self.median_idf) / total
if logTF:
freq[k] *= math.log2(self.idf_freq.get(kw, self.median_idf)) / total
else:
freq[k] *= self.idf_freq.get(kw, self.median_idf) / total

if withWeight:
tags = sorted(freq.items(), key=itemgetter(1), reverse=True)
Expand Down