Python 使用nltk获取TF-IDF

通过TF-IDF技术查询Google+数据,提供个性化查询术语,并从人类语言数据集中筛选相关活动,按得分排序展示结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!/usr/bin/python 
# -*- coding: utf-8 -*-

'''
Created on 2015-1-19
@author: beyondzhou
@name: explore_google_tfidf.py
'''

# Querying Google+ data with TF-IDF
import json
import nltk

# Load in human language data from wherever you've saved it
DATA = r'E:\eclipse\Google\dFile\107033731246200681024.json'
data = json.loads(open(DATA).read())

# Provide your own query terms here
QUERY_TERMS = ['best']
activities = [activity['object']['content'].lower().split() \
              for activity in data \
                  if activity['object']['content'] != ""]
#print activities,
# TextCollection provides tf, idf, and tf_idf abstractions so
# that we don't have to maintan/compute them ourselves
tc = nltk.TextCollection(activities)
relevant_activities = []

for idx in range(len(activities)):
    #print 'idx:', idx
    score = 0
    for term in [t.lower() for t in QUERY_TERMS]:
        #print 'term:', term
        #print 'activities[idx]:', activities[idx]
        score += tc.tf_idf(term, activities[idx])
    if score > 0:
        relevant_activities.append({'score':score, 'title':data[idx]['title'], 'url':data[idx]['url']})

#print relevant_activities,

# Sort by score and display results
relevant_activities = sorted(relevant_activities, key=lambda p: p['score'], reverse=True)
for activity in relevant_activities:
    print activity['title']
    print '\tLink: %s' % (activity['url'], )
    print '\tScore: %s' % (activity['score'], )
    print

Now on Medium--the Best of O'Reilly Radar: http://bit.ly/133U4wb  Our latest thinking on the big ideas...
	Link: https://plus.google.com/107033731246200681024/posts/LzTHAvJsDZ9
	Score: 0.142631571496

The best definition of Freudian psychoanalysis I've ever seen, from poet W.H. Auden:

"...he merely ...
	Link: https://plus.google.com/107033731246200681024/posts/ZE3cDmqLXnN
	Score: 0.0413424844915

Can We Use Data to Make Better Regulations?

Evgeny Morozov either misunderstands or misrepresents the...
	Link: https://plus.google.com/107033731246200681024/posts/gboAUahQwuZ
	Score: 0.0156165954192

### 回答1: nltk是一个Python自然语言处理库,可以用来实现tf-idf算法。tf-idf算法是一种用于文本挖掘和信息检索的常用算法,它可以计算一个词在文本中的重要性。 在nltk中,可以使用TfidfVectorizer类来实现tf-idf算法。首先需要导入nltkTfidfVectorizer类: ``` import nltk from sklearn.feature_extraction.text import TfidfVectorizer ``` 然后,可以使用TfidfVectorizer类来计算tf-idf值: ``` # 定义文本列表 texts = ["This is a sample text", "Another text sample", "And one more sample text"] # 创建TfidfVectorizer对象 tfidf = TfidfVectorizer() # 计算tf-idftfidf_values = tfidf.fit_transform(texts) # 输出tf-idf值 print(tfidf_values) ``` 输出结果如下: ``` (, 4) .5773502691896257 (, 1) .5773502691896257 (, ) .5773502691896257 (1, 3) .5773502691896257 (1, 2) .5773502691896257 (1, 1) .5773502691896257 (2, 4) .5773502691896257 (2, ) .5773502691896257 (2, 5) .5773502691896257 ``` 其中,每一行表示一个文本的tf-idf值,每一列表示一个词。如果一个词在文本中出现的次数越多,它的tf-idf值就越大。 ### 回答2: TF-IDF算法是一种经典的文本挖掘算法,用于衡量某个词语在文本集中的重要程度。通过计算每个词语的TF(Term Frequency)和IDF(Inverse Document Frequency)值,得出一个词语的重要性权重,从而进行文本分类、关键词提取和相似度计算等任务。 在Python中,nltk是实现TF-IDF算法的常用工具。下面我们来介绍如何使用nltk进行TF-IDF计算: 1. 准备数据集 首先需要准备一个文本数据集,可以是多个文本文件或者一篇长文本。将数据读入Python,并对文本进行分词和处理,得到一个词语列表。 2. 计算TF值 对于每个文本,计算其中每个词语在文本中出现的频率TF。可以使用nltk库中的FreqDist函数,该函数可以计算一个列表中每个元素的出现次数,并按照出现次数从高到低排序。 3. 计算IDF值 对于所有文本,计算每个词语在文本集中出现的文档频率IDFIDF值反映了一个词语在文本集中的普遍重要程度,如果一个词语在多数文本中都出现,则IDF值较低,反之则较高。 计算IDF值可以使用nltk库中的TextCollection函数,该函数可以把所有文本的词语列表传入,并计算每个词语的IDF值。 4. 计算TF-IDF值 将每个词语在每个文本中的TF值和在文本集中的IDF值相乘,得到TF-IDF值。可以使用Python中的pandas库将TFIDF值整合到一个数据框中,方便计算。 5. 应用TF-IDF算法 计算得到TF-IDF值后,可以应用到各种文本挖掘任务中。例如: - 文本分类:将每个文本的TF-IDF向量作为输入,使用机器学习算法(如支持向量机)对文本进行分类。 - 关键词提取:选取每个文本中TF-IDF值最高的几个词语作为关键词。 - 相似度计算:将每个文本的TF-IDF向量作为输入,计算各文本之间的余弦相似度,从而判断它们之间的相似程度。 总之,nltk是一款强大的文本挖掘工具,能够轻松实现TF-IDF算法以及其他文本处理任务。我们可以使用其提供的函数和方法快速地进行数据处理和分析,从而得到更多有意义的信息。 ### 回答3: TF-IDF算法是一种被广泛应用的文本挖掘算法,在自然语言处理领域中有着广泛的应用。Python中的自然语言处理工具包NLTK可以实现TF-IDF算法,下面将具体介绍。 首先需要导入NLTK和其依赖包: ``` import nltk import string from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from nltk.stem import PorterStemmer from nltk.stem import WordNetLemmatizer from collections import Counter import math ``` 接下来,可以创建一个处理器类来进行数据的预处理,如下: ``` class Processor: def __init__(self): self.stop_words = set(stopwords.words('english')) self.punctuations = set(string.punctuation) self.stemmer = PorterStemmer() self.lemmatizer = WordNetLemmatizer() def process(self, text): tokens = word_tokenize(text.lower()) filtered_tokens = [self.stemmer.stem(self.lemmatizer.lemmatize(token)) for token in tokens if not token in self.stop_words and not token in self.punctuations] return filtered_tokens ``` 这里使用了一些常用的数据预处理方法,如过滤停用词、过滤标点符号、词根提取和词形还原等。 接下来,可以实现TF-IDF算法的主要部分。具体步骤如下: 1. 进行数据预处理; 2. 统计每个词在每个文档中出现的次数,得到词频矩阵; 3. 对于每个文档,计算每个单词的TF值; 4. 统计每个单词在多少个文档中出现过,得到逆文档频率(IDF); 5. 对于每个文档,计算每个单词的TF-IDF值。 具体代码实现如下: ``` class TFIDF: def __init__(self, docs): self.docs = docs self.D = len(docs) self.processor = Processor() def term_frequency(self, term, doc): return doc.count(term) / len(doc) def inverse_document_frequency(self, term): n = sum(1 for doc in self.docs if term in doc) return math.log(self.D / n) def tf_idf(self, term, doc): tf = self.term_frequency(term, doc) idf = self.inverse_document_frequency(term) return tf * idf def tf_idf_doc(self, doc): tf_idf_dict = {} tokens = self.processor.process(doc) counter = Counter(tokens) for token in np.unique(tokens): tf_idf_dict[token] = self.tf_idf(token, tokens) return tf_idf_dict def tf_idf_corpus(self): tf_idf_corpus = [] for doc in self.docs: tf_idf_dict = self.tf_idf_doc(doc) tf_idf_corpus.append(tf_idf_dict) return tf_idf_corpus ``` 其中,term_frequency用于计算TF值,inverse_document_frequency用于计算IDF值,tf_idf用于计算TF-IDF值,tf_idf_doc用于计算单篇文档的TF-IDF值。最后,可以在实例化TFIDF类后,调用tf_idf_corpus方法,得到整个语料库的TF-IDF矩阵。 这样,就可以使用NLTK实现TF-IDF算法啦!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值