Python词频统计

1.合并数据文件

import os
import os.path   #文件夹遍历函数  

files = os.listdir('./raw_data')  #特定目录下的文件存入列表
f=open('result.txt','w')    #打开当前目录下的result.txt文件,如果没有则创建

for file in files:
   filepath = './raw_data/'+file
   for line in open(filepath):     #遍历单个文件,读取行数
       f.writelines(line)
   f.write('\n')

f.close()

2.词频统计

import re
import jieba
from collections import Counter
import csv

# 读入数据文件文件
content = open('all_data.txt',encoding="gbk").read()

#数据清理
content = re.sub(r'\n+','',content) #去除换行符
content = re.sub(r'\W+',' ',content) #符号替换为空白
content = re.sub(r' +','',content)  #去除空格

#分词
seg_list = list(jieba.cut(content))
#print("分词结果: \n","/".join(seg_list[:99])) 

#去停用词
stopwords = open('stopwords.txt',encoding="utf-8").read() 
stopwords = stopwords.split('\n')       #字符串按'\n'分割,构建列表类型
#print("停用词: \n",",".join(stopwords[:20]))      #显示部分停用词,第一个为空格
final_content = []
for seg in seg_list:
    if seg not in stopwords:
        final_content.append(seg)
#print("分词结果: \n","/".join(final_content[:99]))     #显示部分处理结果

#词频统计
counting_words = Counter(final_content)
common_words = counting_words.most_common(50)
common_words.sort(key = lambda x:x[1], reverse = True)
#print(commo_words)

#词频写入csv
with open('word_excel.csv', 'w', encoding = 'utf-8', newline = '') as csvfile:
    write = csv.writer(csvfile)  #创建一个csv的writer对象用于写每一行内容
    write.writerow(['词组','词频'])  #写表格表头
    write.writerows(common_words)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 词频计算部分 原数据从mysql中获取. 我要统计返回行tag属性中包含的tag词频。 返回数据的每一个row都是...
    Kaidi_G阅读 8,858评论 2 3
  • 项目概述 通过两个Python文件实现一个简单的词频统计。 本工程共有4个文件: file01:要统计的词频文件。...
    狼牙战士阅读 5,324评论 0 0
  • 最近工作蛮忙的,就简单练习一下python基础吧。 本周的练习是词频统计,主要使用了以下几个函数: text.sp...
    Sudden阅读 3,511评论 0 3
  • 统计结果 从图中我们可以看出,国家在十三五期间,“生态”出现的最多依次为建设,环境等,可以看出,国家十三五在生态环...
    TowardsCHEND阅读 2,600评论 0 0
  • 场景: 现在要统计一个文本中的词频,然后按照频率的降序进行排列
    妈耶0000阅读 1,547评论 0 0