python中文分词和词频统计如何实现(python,开发技术)

时间:2024-05-04 21:06:59 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

一、文本导入

我准备了一个名为abstract.txt的文本文件

python中文分词和词频统计如何实现

接着是在网上下载了stopword.txt(用于结巴分词时的停用词)

python中文分词和词频统计如何实现

有一些是自己觉得没有用加上去的

另外建立了自己的词典extraDict.txt

python中文分词和词频统计如何实现

准备工作做好了,就来看看怎么使用吧!

二、使用步骤

1.引入库

代码如下:

importjiebafromjieba.analyseimportextract_tagsfromsklearn.feature_extraction.textimportTfidfVectorizer

2.读入数据

代码如下:

jieba.load_userdict('extraDict.txt')#导入自己建立词典

3.取出停用词表

defstopwordlist():stopwords=[line.strip()forlineinopen('chinesestopwords.txt',encoding='UTF-8').readlines()]#---停用词补充,视具体情况而定---i=0foriinrange(19):stopwords.append(str(10+i))#----------------------returnstopwords

4.分词并去停用词(此时可以直接利用python原有的函数进行词频统计)

defseg_word(line):#seg=jieba.cut_for_search(line.strip())seg=jieba.cut(line.strip())temp=""counts={}wordstop=stopwordlist()forwordinseg:ifwordnotinwordstop:ifword!='':temp+=wordtemp+='\n'counts[word]=counts.get(word,0)+1#统计每个词出现的次数returntemp#显示分词结果#returnstr(sorted(counts.items(),key=lambdax:x[1],reverse=True)[:20])#统计出现前二十最多的词及次数

5.输出分词并去停用词的有用的词到txt

defoutput(inputfilename,outputfilename):inputfile=open(inputfilename,encoding='UTF-8',mode='r')outputfile=open(outputfilename,encoding='UTF-8',mode='w')forlineininputfile.readlines():line_seg=seg_word(line)outputfile.write(line_seg)inputfile.close()outputfile.close()returnoutputfile

6.函数调用

if__name__=='__main__':print("__name__",__name__)inputfilename='abstract.txt'outputfilename='a1.txt'output(inputfilename,outputfilename)

7.结果

python中文分词和词频统计如何实现

附:输入一段话,统计每个字母出现的次数

先来讲一下思路:

例如给出下面这样一句话

Love is more than a word
it says so much.
When I see these four letters,
I almost feel your touch.
This is only happened since
I fell in love with you.
Why this word does this,
I haven’t got a clue.

那么想要统计里面每一个单词出现的次数,思路很简单,遍历一遍这个字符串,再定义一个空字典count_dict,看每一个单词在这个用于统计的空字典count_dict中的key中存在否,不存在则将这个单词当做count_dict的键加入字典内,然后值就为1,若这个单词在count_dict里面已经存在,那就将它对应的键的值+1就行

下面来看代码:

#定义字符串sentences="""#字符串很长时用三个引号Loveismorethanaworditsayssomuch.WhenIseethesefourletters,Ialmostfeelyourtouch.ThisisonlyhappenedsinceIfellinlovewithyou.Whythisworddoesthis,Ihaven'tgotaclue."""#具体实现#将句子里面的逗号去掉,去掉多种符号时请用循环,这里我就这样吧sentences=sentences.replace(',','')sentences=sentences.replace('.','')#将句子里面的.去掉sentences=sentences.split()#将句子分开为单个的单词,分开后产生的是一个列表sentences#print(sentences)count_dict={}forsentenceinsentences:ifsentencenotincount_dict:#判断是否不在统计的字典中count_dict[sentence]=1else:#判断是否不在统计的字典中count_dict[sentence]+=1forkey,valueincount_dict.items():print(f"{key}出现了{value}次")

输出结果是这样:

python中文分词和词频统计如何实现

 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:python中文分词和词频统计如何实现的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:Android如何解决所有双击优化的问题下一篇:

11 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18