nltk-比较英文文档相似度-完整实例

说明:

* 其中基准数据,可以来自外部,处理过程为:

     - 处理为词袋

     - 经过数据集的tfidf结果

* 无法处理中文

     - 分词器不支持

* 未另外加载语料库

#!/usr/bin/env python
#-*-coding=utf-8-*-
 
"""原始数据"""
#缩水版的courses,实际数据的格式应该为 课程名\t课程简介\t课程详情,并已去除html等干扰因素
courses = ['Writing II: Rhetorical Composing', 'Genetics and Society: A Course for Educators', 'General Game Playing', 'Genes and the Human Condition (From Behavior to Biotechnology)', 'A Brief History of Humankind', 'New Models of Business in Society', 'Analyse Numrique pour Ingnieurs', 'Evolution: A Course for Educators', 'Coding the Matrix: Linear Algebra through Computer Science Applications', 'The Dynamic Earth: A Course for Educators']
#实际的 courses_name = [course.split('\t')[0] for course in courses]
courses_name = ['Writing II: Rhetorical Composing', 'Genetics and Society: A Course for Educators', 'General Game Playing', 'Genes and the Human Condition (From Behavior to Biotechnology)', 'A Brief History of Humankind', 'New Models of Business in Society', 'Analyse Numrique pour Ingnieurs', 'Evolution: A Course for Educators', 'Coding the Matrix: Linear Algebra through Computer Science Applications', 'The Dynamic Earth: A Course for Educators']
 
 
 
"""预处理(easy_install nltk)"""
 
#引入nltk
import nltk
#nltk.download()    #下载要用的语料库等,时间比较长,最好提前准备好
 
#分词
from nltk.corpus import brown
texts_lower = [[word for word in document.lower().split()] for document in courses]
from nltk.tokenize import word_tokenize
texts_tokenized = [[word.lower() for word in word_tokenize(document)] for document in courses]
 
#去除停用词
from nltk.corpus import stopwords
english_stopwords = stopwords.words('english')
texts_filtered_stopwords = [[word for word in document if not word in english_stopwords] for document in texts_tokenized]
#去除标点符号
english_punctuations = [',', '.', ':', ';', '?', '(', ')', '[', ']', '&', '!', '*', '@', '#', '$', '%']
texts_filtered = [[word for word in document if not word in english_punctuations] for document in texts_filtered_stopwords]
 
#词干化
from nltk.stem.lancaster import LancasterStemmer
st = LancasterStemmer()
texts_stemmed = [[st.stem(word) for word in docment] for docment in texts_filtered]
 
 
#去除过低频词
all_stems = sum(texts_stemmed, [])
stems_once = set(stem for stem in set(all_stems) if all_stems.count(stem) == 1)
texts = [[stem for stem in text if stem not in stems_once] for text in texts_stemmed]
 
"""
注意:本例子中只用了course_name字段,大多数word频率过低,造成去除低频词后,有些document可能为空
          因此后面的处理结果只做示范
"""
 
 
"""
引入gensim,正式开始处理(easy_install gensim)
 
输入:
     1.去掉了停用词
     2.去掉了标点符号
     3.处理为词干
     4.去掉了低频词
 
"""
from gensim import corpora, models, similarities
 
#为了能看到过程日志
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
 
dictionary = corpora.Dictionary(texts)
corpus = [dictionary.doc2bow(text) for text in texts]     #doc2bow(): 将collection words 转为词袋,用两元组(word_id, word_frequency)表示
tfidf = models.TfidfModel(corpus)
corpus_tfidf = tfidf[corpus]
 
#拍脑袋的:训练topic数量为10的LSI模型
lsi = models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=10)
index = similarities.MatrixSimilarity(lsi[corpus])     # index 是 gensim.similarities.docsim.MatrixSimilarity 实例
 
 
"""
对具体对象相似度匹配
"""
#选择一个基准数据
ml_course = texts[2]
ml_bow = dictionary.doc2bow(ml_course)     
#在上面选择的模型数据 lsi 中,计算其他数据与其的相似度
ml_lsi = lsi[ml_bow]     #ml_lsi 形式如 (topic_id, topic_value)
sims = index[ml_lsi]     #sims 是最终结果了, index[xxx] 调用内置方法 __getitem__() 来计算ml_lsi
#排序,为输出方便
sort_sims = sorted(enumerate(sims), key=lambda item: -item[1])
 
#查看结果
print sort_sims[0:10]   #看下前10个最相似的,第一个是基准数据自身
print courses_name[2]   #看下实际最相似的数据叫什么



转载于:https://my.oschina.net/stevie/blog/692029

Python中的文本相似度可以通过基于TF-IDF和余弦相似度算法来实现。TF-IDF(Term Frequency-Inverse Document Frequency)是用于评估一个词语在一个文档中的重要程度的方法。 首先,我们需要使用Python中的文本处理库(如nltk)来对文本进行预处理,包括分词、去除停用词、词干化等。接下来,我们可以使用sklearn库中的TF-IDF向量化器来将文本转换为TF-IDF特征向量。 然后,我们可以使用余弦相似度算法来计算两个文本之间的相似度。余弦相似度是通过计算两个向量之间的夹角来度量它们的相似程度的。 以下是一个简单的示例代码: ```python import nltk from nltk.corpus import stopwords from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity def preprocess_text(text): # 分词 tokens = nltk.word_tokenize(text) # 去除停用词 stop_words = set(stopwords.words('english')) tokens = [token for token in tokens if token.lower() not in stop_words] # 词干化 stemmer = nltk.PorterStemmer() tokens = [stemmer.stem(token) for token in tokens] # 返回处理后的文本 return " ".join(tokens) def calculate_similarity(text1, text2): # 预处理文本 processed_text1 = preprocess_text(text1) processed_text2 = preprocess_text(text2) # 转换为TF-IDF特征向量 vectorizer = TfidfVectorizer() tfidf_matrix = vectorizer.fit_transform([processed_text1, processed_text2]) # 计算余弦相似度 cosine_sim = cosine_similarity(tfidf_matrix[0], tfidf_matrix[1]) # 返回相似度 return cosine_sim[0][0] text1 = "今天天气不错" text2 = "今天天气很好" similarity = calculate_similarity(text1, text2) print("文本1和文本2的相似度为:", similarity) ``` 在以上示例中,我们先对文本进行了预处理,并使用TF-IDF向量化器将其转换为特征向量。然后,我们使用余弦相似度算法计算了文本1和文本2之间的相似度,并输出结果。 这只是一个简单的示例,实际应用中可能需要更多的预处理步骤和参数调整来获得更好的结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值