文本相似度(词频统计)的流程
- 实现流程的简介
- 度量文本间的相似性
- 使用词频表示文本特征
- 文本中单词出现的频率或次数
- NLTK实现词频统计
- 文本相似度分析的流程
- 导入模块
- import nltk
- from nltk import FreqDist # 导入词频统计模块FreqDist
- 先定义进行分析的几个文本
- text1 = 'I like the movie so much '
- text2 = 'That is a good movie '
- text3 = 'This is a great one '
- text4 = 'That is a really bad movie '
- text5 = 'This is a terrible movie'
- 定义取出词频最好的n个单词的方法(词频统计方法)
- def get_most_common_words(n, *args):
- """将文本内容汇总,并获取统计每个单词的词频的列表"""
- text = [text for text in args]
- text = ''.join(text)
- words = nltk.word_tokenize(text) # 对文本进行分词处理
- freq_dist = FreqDist(words) # 1.生成每个单词的词频统计结果,生成词频统计对象
- most_common_words = freq_dist.most_common(n) # 2.取出最高频率的n个单词,返回列表
- return most_common_words # 输出类似:[('a', 4), ('movie', 4), ('is', 4), ('This', 2), ('That', 2)]
- 定义查找单词所在位置的方法
- def lookup_pos(most_common_words):
- result = {} # 事先设置好存储常用单词的字典
- pos = 0 # 表示常用单词的位置
- for word in get_most_common_words:
- result[word[0]] = pos
- pos += 1
- return result # 返回数据类似:{'movie': 0, 'is': 1, 'a': 2, 'That': 3, 'This': 4}
- 获取词频统计的结果列表
- most_common_words = get_most_common_words(5, text1, text2, text3, text4, text5)
- 记录常用单词的位置,用来进行相似度的判断
- std_pos_dict = lookup_pos(most_common_words)
- 计算新文本常用词的词频分别为多少
- new_text = 'That one is a good movie. This is so good!' # 定义新文本
- freq_vec = [0] * n # 初始化向量,用来存储常用词的词频
- new_words = nltk.word_tokenize(new_text) # 分词处理
- 在“常用单词列表”上计算词频,当出现常用词频时,统计一次
- for new_word in new_words:
- if new_word in list(std_pos_dict.keys()):
- freq_vec[std_pos_dict[new_word]] += 1
- print(freq_vec) ---> [1, 2, 1, 1, 1]
文本分类的分析方法
- TF-IDF (词频-逆文档频率)介绍
- TF-IDF的作用
- 用来描述一个单词对一篇文章的重要程度
- TF, Term Frequency(词频)
- 表示某个词在该文件中出现的次数
- IDF,Inverse Document Frequency(逆文档频率)
- 用于衡量某个词普 遍的重要性。
- TF-IDF(词频-逆文档频率)
- TF-IDF = TF * IDF 用来统计个单词对于一篇文章的重要程度
- 代码示例