美文网首页
Python词频统计

Python词频统计

作者: 云上小白鸽 | 来源:发表于2022-01-11 14:10 被阅读0次

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)

相关文章

  • python统计词频

    一、最终目的 统计四六级真题中四六级词汇出现的频率,并提取对应的例句,最终保存到SQL数据库中。 二、处理过程 1...

  • python统计词频

    一、使用re库进行识别 1、代码 2、参考 python--10行代码搞定词频统计python:统计历年英语四六级...

  • python 词频统计

    """Count words.""" def count_words(s, n): """Return the...

  • Python | 词频统计

    最近工作蛮忙的,就简单练习一下python基础吧。 本周的练习是词频统计,主要使用了以下几个函数: text.sp...

  • Python词频统计

    场景: 现在要统计一个文本中的词频,然后按照频率的降序进行排列

  • Python词频统计

    1.合并数据文件 2.词频统计

  • python词频统计实例

    项目概述 通过两个Python文件实现一个简单的词频统计。 本工程共有4个文件: file01:要统计的词频文件。...

  • Python 进行词频统计

    1. 利用字典map实现 2.利用collections模块中的Counter对象 3. 算法:...

  • Python实现词频统计

    《百年孤独》词频统计 学习更多?欢迎关注本人公众号:Python无忧

  • 教你用Python进行中文词频统计

    Python是用于数据挖掘的利器 用Python可以用来做很多很好玩的东西,下面就来用Python来进行词频统计 ...

网友评论

      本文标题:Python词频统计

      本文链接:https://www.haomeiwen.com/subject/afbbcrtx.html