注:此文章内容均节选自充电了么创始人,CEO兼CTO陈敬雷老师的新书《自然语言处理原理与实战》(人工智能科学与技术丛书)【陈敬雷编著】【清华大学出版社】
自然语言处理系列三十八
Python代码实现词频-逆文档频率(TF-IDF)
请两篇文章讲了算法原理和Java实现TF-IDF,本篇文章使用Python代码实现。
9.2 Python代码实现TF-IDF
TF-IDF基于Python代码如9.2所示。
【代码9.2】 TFIDF.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
#__author__ = '陈敬雷'
import os
import codecs
import math
import operator
print("充电了么 - 专注上班族职业培训和职业技能提升充电学习的在线教育平台")
"""
词频-逆文档频率(TF-IDF)
"""
def fun(filepath): # 遍历文件夹中的所有文件,返回文件list
arr = []
for root, dirs, files in os.walk(filepath):
for fn in files:
arr.append(root+"\\"+fn)
return arr
def wry(txt, path): # 写入txt文件
f = codecs.open(path, 'a', 'utf8')
f.write(txt)
f.close()
return path
def read(path): # 读取txt文件,并返回list
f = open(path, encoding="utf8")
data = []
for line in f.readlines():
data.append(line)
return data
def toword(txtlis): # 将一片文章按照‘/’切割成词表,返回list
wordlist = []
alltxt = ''
for i in txtlis:
alltxt = alltxt+str(i)
ridenter = alltxt.replace('\n', '')
wordlist = ridenter.split('/')
return wordlist
def getstopword(path): # 获取停用词表
swlis = []
for i in read(path):
outsw = str(i).replace('\n', '')
swlis.append(outsw)
return swlis
def getridofsw(lis, swlist): # 去除文章中的停用词
afterswlis = []
for i in lis:
if str(i) in swlist:
continue
else:
afterswlis.append(str(i))
return afterswlis
def freqword(wordlis): # 统计词频,并返回字典
freword = {}
for i in wordlis:
if str(i) in freword:
count = freword[str(i)]
freword[str(i)] = count+1
else:
freword[str(i)] = 1
return freword
def corpus(filelist, swlist): # 建立语料库
alllist = []
for i in filelist:
afterswlis = getridofsw(toword(read(str(i))), swlist)
alllist.append(afterswlis)
return alllist
def wordinfilecount(word, corpuslist): # 查出包含该词的文档数
count = 0 # 计数器
for i in corpuslist:
for j in i:
if word in set(j): # 只要文档出现该词,这计数器加1,所以这里用集合
count = count+1
else:
continue
return count
def tf_idf(wordlis, filelist, corpuslist): # 计算TF-IDF,并返回字典
outdic = {}
tf = 0
idf = 0
dic = freqword(wordlis)
outlis = []
for i in set(wordlis):
tf = dic[str(i)]/len(wordlis) # 计算TF:某个词在文章中出现的次数/文章总词数
# 计算IDF:log(语料库的文档总数/(包含该词的文档数+1))
idf = math.log(len(filelist)/(wordinfilecount(str(i), corpuslist)+1))
tfidf = tf*idf # 计算TF-IDF
outdic[str(i)] = tfidf
orderdic = sorted(outdic.items(), key=operator.itemgetter(
1), reverse=True) # 给字典排序
return orderdic
def befwry(lis): # 写入预处理,将list转为string
outall = ''
for i in lis:
ech = str(i).replace("('", '').replace("',", '\t').replace(')', '')
outall = outall+'\t'+ech+'\n'
return outall
def main():
#停用词是出现次数最多的词比如"的"、"是"、"在"----这一类最常用的词。
swpath = r'stopwords.txt'#停用词表路径文件,内容每个停用词占用一行
swlist = getstopword(swpath) # 获取停用词表列表
filepath = r'D:\充电了么TFIDF'#输入的文件夹,文件夹下面有多个文档文件
filelist = fun(filepath) # 获取文件列表
wrypath = r'TFIDF.txt'#输出结果文件
corpuslist = corpus(filelist, swlist) # 建立语料库
outall = ''
for i in filelist:
afterswlis = getridofsw(toword(read(str(i))), swlist) # 获取每一篇已经去除停用的词表
tfidfdic = tf_idf(afterswlis, filelist, corpuslist) # 计算TF-IDF
titleary = str(i).split('\\')
title = str(titleary[-1]).replace('utf8.txt', '')
echout = title+'\n'+befwry(tfidfdic)
print(title+' is ok!')
outall = outall+echout
print(wry(outall, wrypath)+' 计算完成并输出到文件!')
if __name__ == '__main__':
main()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
条件随机场(CRF)算法原理
条件随机场(CRF)是Conditional Random Fields的缩写,即条件随机域,是Lafferty于2001年,在最大熵模型和隐马尔科夫模型的基础上,提出的一种判别式概率无向图学习模型,是一种用于标注和切分有序数据的条件概率模型,近年来在分词、词性标注和命名实体识别等序列标注任务中取得了很好的效果。也就是说要理解条件随机场需要先了解马尔可夫链、隐马尔可夫模型(HMM)的一些基本概念。下一篇文章详细讲解,敬请关注!
总结
此文章有对应的配套新书教材和视频:
【配套新书教材】
《自然语言处理原理与实战》(人工智能科学与技术丛书)【陈敬雷编著】【清华大学出版社】
新书特色:本书从自然语言处理基础开始,逐步深入各种NLP热点前沿技术,使用了Java和Python两门语言精心编排了大量代码实例,契合公司实际工作场景技能,侧重实战。
全书共分为19章,详细讲解中文分词、词性标注、命名实体识别、依存句法分析、语义角色标注、文本相似度算法、语义相似度计算、词频-逆文档频率(TF-IDF)、条件随机场、新词发现与短语提取、搜索引擎Solr Cloud和Elasticsearch、Word2vec词向量模型、文本分类、文本聚类、关键词提取和文本摘要、自然语言模型(Language Model)、分布式深度学习实战等内容,同时配套完整实战项目,例如对话机器人实战、搜索引擎项目实战、推荐算法系统实战。
本书理论联系实践,深入浅出,知识点全面,通过阅读本书,读者不仅可以理解自然语言处理的知识,还能通过实战项目案例更好地将理论融入实际工作中。
【配套视频】
自然语言处理NLP原理与实战 视频教程【陈敬雷】
视频特色:《自然语言处理NLP原理与实战》包含了互联网公司前沿的热门算法的核心原理,以及源码级别的应用操作实战,直接讲解自然语言处理的核心精髓部分,自然语言处理从业者或者转行自然语言处理者必听视频!
上一篇:自然语言处理系列三十七》词频-逆文档频率TF-IDF》Java代码实现
下一篇:自然语言处理系列三十九》条件随机场(CRF)算法原理
评论记录:
回复评论: