python基础入门:3.5实战:词频统计工具

Python词频统计终极指南:字典与排序的完美结合

import re
from collections import defaultdict

def word_frequency_analysis(file_path, top_n=10):
    """
    完整的词频统计解决方案
    :param file_path: 文本文件路径
    :param top_n: 显示前N个高频词
    :return: 排序后的词频列表
    """
    # 文本预处理管道
    with open(file_path, 'r', encoding='utf-8') as f:
        text = f.read().lower()  # 统一小写
        words = re.findall(r'\b[a-z]+\b', text)  # 提取纯单词

    # 使用defaultdict简化计数
    word_counts = defaultdict(int)
    for word in words:
        word_counts[word] += 1

    # 多级排序:先按频率降序,再按字母顺序
    sorted_words = sorted(word_counts.items(),
                         key=lambda x: (-x[1], x[0]))
  
    # 格式化输出
    print(f"{" 单词 ":<15}{" 频率 ":<10}")
    print("-"*25)
    for word, count in sorted_words[:top_n]:
        print(f"{word:<15}{count:<10}")
    return sorted_words

# 使用示例
analysis_result = word_frequency_analysis("sample.txt", top_n=15)

核心实现解析

1. 文本预处理优化

# 进阶正则表达式处理
text = """
Python's 3.10 version introduced pattern matching!
Don't-miss-this-feature.
"""

# 处理步骤分解
cleaned = re.sub(r"[^\w\s-]", "", text.lower())  # 保留连字符
words = re.findall(r"\b[\w-]+\b", cleaned)  # 匹配带连字符的单词
# 结果:["python's", "version", ...] → 需要进一步过滤

# 最终优化版正则
words = re.findall(r"\b(?![\d_]+)[a-z'-]+\b", text.lower())

预处理流程图

原始文本 → 小写转换 → 标点过滤 → 单词提取 → 有效词过滤

2. 统计方法对比

# 方法1:原生字典
counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1

# 方法2:defaultdict
counts = defaultdict(int)
for word in words:
    counts[word] += 1

# 方法3:Counter
from collections import Counter
counts = Counter(words)

性能对比表

方法时间复杂度内存使用可读性
原生字典O(n)中等
defaultdictO(n)
CounterO(n)最高

进阶排序技巧

1. 多级排序实现

# 主要排序规则:频率降序 → 次要规则:字母升序
sorted_words = sorted(word_counts.items(),
                      key=lambda x: (-x[1], x[0]))

# 等效写法
sorted_words = sorted(word_counts.items(),
                      key=lambda x: (x[1], x[0]),
                      reverse=True)
sorted_words = sorted(sorted_words,
                      key=lambda x: x[0])

2. 频率分布直方图

def plot_frequency(sorted_list):
    """使用matplotlib可视化结果"""
    import matplotlib.pyplot as plt
  
    words, counts = zip(*sorted_list[:20])
    plt.figure(figsize=(12, 6))
    plt.barh(words[::-1], counts[::-1])  # 降序排列显示
    plt.xlabel('Frequency')
    plt.title('Top 20 Frequent Words')
    plt.tight_layout()
    plt.show()

plot_frequency(analysis_result)

企业级功能扩展

1. 停用词过滤

def load_stopwords(file='stopwords.txt'):
    with open(file) as f:
        return set(line.strip() for line in f)

stopwords = load_stopwords()
filtered_words = [w for w in words if w not in stopwords]

2. 词干提取

from nltk.stem import PorterStemmer
stemmer = PorterStemmer()

processed_words = [stemmer.stem(w) for w in filtered_words]

3. 多文件批处理

import glob

def batch_analysis(folder_path):
    total_counts = defaultdict(int)
    for file in glob.glob(f"{folder_path}/*.txt"):
        with open(file) as f:
            words = re.findall(r'\b[a-z]+\b', f.read().lower())
            for word in words:
                total_counts[word] += 1
    return sorted(total_counts.items(), key=lambda x: -x[1])

性能优化策略

1. 内存优化

# 生成器处理大文件
def process_large_file(file_path):
    with open(file_path) as f:
        for line in f:
            words = re.findall(r'\b[a-z]+\b', line.lower())
            yield from words

# 流式处理
counts = defaultdict(int)
for word in process_large_file("big_data.txt"):
    counts[word] += 1

2. 多线程加速

from concurrent.futures import ThreadPoolExecutor

def parallel_count(file_chunks):
    with ThreadPoolExecutor() as executor:
        results = executor.map(count_chunk, file_chunks)
    # 合并结果
    total = defaultdict(int)
    for partial in results:
        for k, v in partial.items():
            total[k] += v
    return total

扩展应用

  • 结合TF-IDF算法实现关键词提取
  • 实时文本流分析(使用滑动窗口)
  • 情感分析中的特征词统计
  • 自动补全系统的词频基础
# 实时分析示例
from collections import deque

class StreamingAnalyzer:
    def __init__(self, window_size=1000):
        self.window = deque(maxlen=window_size)
        self.counts = defaultdict(int)
  
    def add_text(self, text):
        words = re.findall(r'\b[a-z]+\b', text.lower())
        for word in words:
            # 处理过期词
            if len(self.window) == self.window.maxlen:
                old_word = self.window.popleft()
                self.counts[old_word] -= 1
                if self.counts[old_word] == 0:
                    del self.counts[old_word]
            # 更新新词
            self.window.append(word)
            self.counts[word] += 1
  
    def get_top_words(self, n=10):
        return sorted(self.counts.items(), key=lambda x: -x[1])[:n]

性能基准测试(百万级单词):

  • 基础版本:2.8秒
  • 内存优化版:1.5秒
  • 多线程版:0.8秒

下一步学习

  • 自然语言处理基础:NLTK库实战
  • 大数据处理:PySpark词频统计
  • 实时计算:Kafka流处理集成
  • 可视化进阶:Plotly动态图表

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/967172.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

时序数据库:Influxdb详解

文章目录 一、简介1、简介2、官网 二、部署1、安装2、配置&#xff08;1&#xff09;用户初始化 三、入门&#xff08;Web UI&#xff09;1、加载数据&#xff08;1&#xff09;上传数据文件&#xff08;2&#xff09;代码接入模板 2、管理存储桶&#xff08;1&#xff09;创建…

unity学习32:角色相关1,基础移动控制

目录 0 应用商店 1 角色上新增CharacterController 组件 1.1 角色上新增CharacterController 组件 1.2 如果没有这个则会报错 2 速度 2.1 默认速度&#xff0c;按帧率计算 2.2 修改速度为按时间计算 2.3 movespeed&#xff0c;基础是1米/秒&#xff0c;这个就是每 move…

Centos Ollama + Deepseek-r1+Chatbox运行环境搭建

Centos Ollama Deepseek-r1Chatbox运行环境搭建 内容介绍下载ollama在Ollama运行DeepSeek-r1模型使用chatbox连接ollama api 内容介绍 你好&#xff01; 这篇文章简单讲述一下如何在linux环境搭建 Ollama Deepseek-r1。并在本地安装的Chatbox中进行远程调用 下载ollama 登…

mysql8.0使用pxc实现高可用

环境准备 准备三台虚拟机&#xff0c;其对应的主机名和IP地址为 pxc-1192.168.190.129pxc-2192.168.190.133pxc-3192.168.190.134 解析,都要做解析 测试 下载pxc的安装包&#xff0c; 官网&#xff1a;https://www.percona.com/downloads 选择8.0的版本并下载&#xff0c;…

LabVIEW污水生化处理在线监测

污水处理是环保领域的重要工作&#xff0c;传统污水处理方法在监测方面存在实时性差、操作不便等问题。为解决这些问题&#xff0c;本项目设计并实现了一套基于LabVIEW的污水生化处理在线监测平台&#xff0c;能够实时监测污水处理过程中的关键参数&#xff0c;如温度、pH值、溶…

【AI学习】关于 DeepSeek-R1的几个流程图

遇见关于DeepSeek-R1的几个流程图&#xff0c;清晰易懂形象直观&#xff0c;记录于此。 流程图一 来自文章《Understanding Reasoning LLMs》&#xff0c; 文章链接&#xff1a;https://magazine.sebastianraschka.com/p/understanding-reasoning-llms?continueFlagaf07b1a0…

vs封装dll 给C#使用

一&#xff0c;vs创建控制台应用 创建控制台应用得好处时&#xff0c;我们可以自己测试接口&#xff0c;如果接口没有问题&#xff0c;改成dll重新编译一遍就可以。 二&#xff0c; 创建一个c 类&#xff0c;将所需提供得功能 封装到类中。 这样可以将 所有功能&#xff0c;进…

ubuntu20使用tigervnc远程桌面配置记录

一、安装tigervnc sudo apt install tigervnc-common sudo apt install tigervnc-standalone-server二、增加配置文件 安装完后新增配置文件&#xff1a;vim ~/.vnc/xstartup #!/bin/sh #Uncomment the following two lines for normal desktop: #unset SESSION_MANAGER #ex…

DeepSeek使用技巧大全(含本地部署教程)

在人工智能技术日新月异的今天&#xff0c;DeepSeek 作为一款极具创新性和实用性的 AI&#xff0c;在众多同类产品中崭露头角&#xff0c;凭借其卓越的性能和丰富的功能&#xff0c;吸引了大量用户的关注。 DeepSeek 是一款由国内顶尖团队研发的人工智能&#xff0c;它基于先进…

网络原理之HTTPS(如果想知道网络原理中有关HTTPS的知识,那么只看这一篇就足够了!)

前言&#xff1a;随着互联网安全问题日益严重&#xff0c;HTTPS已成为保障数据传输安全的标准协议&#xff0c;通过加密技术和身份验证&#xff0c;HTTPS有效防止数据窃取、篡改和中间人攻击&#xff0c;确保通信双方的安全和信任。 ✨✨✨这里是秋刀鱼不做梦的BLOG ✨✨✨想要…

MySQL 8.0.41 终端修改root密码

1.在 MySQL 命令行中&#xff0c;运行以下命令修改密码 ALTER USER rootlocalhost IDENTIFIED BY new_password; 其中&#xff0c;new_password替换为你想要设置的新密码 2.退出 MySQL终端&#xff0c;重新打开&#xff0c;使用新密码进入&#xff0c;修改成功

TCP服务器与客户端搭建

一、思维导图 二、给代码添加链表 【server.c】 #include <stdio.h> #include <sys/socket.h> #include <sys/types.h> #include <fcntl.h> #include <arpa/inet.h> #include <unistd.h> #include <stdlib.h> #include <string.…

JVM春招快速学习指南

1.说在前面 在Java相关岗位的春/秋招面试过程中&#xff0c;JVM的学习是必不可少的。本文主要是通过《深入理解Java虚拟机》第三版来介绍JVM的学习路线和方法&#xff0c;并对没有过JVM基础的给出阅读和学习建议&#xff0c;尽可能更加快速高效的进行JVM的学习与秋招面试的备战…

kafka服务端之副本

文章目录 概述副本剖析失效副本ISR的伸缩LWLEO与HW的关联LeaderEpoch的介入数据丢失的问题数据不一致问题Leader Epoch数据丢失数据不一致 kafka为何不支持读写分离 日志同步机制可靠性分析 概述 Kafka中采用了多副本的机制&#xff0c;这是大多数分布式系统中惯用的手法&…

aarch64 Ubuntu20.04 安装docker

安装 docker 依赖项&#xff1a;sudo apt-get update sudo apt-get install apt-transport-https ca-certificates curl gnupg lsb-release添加 Docker GPG 密钥&#xff1a;curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyr…

校园网规划方案

个人博客站—运维鹿: http://www.kervin24.top CSDN博客—做个超努力的小奚&#xff1a; https://blog.csdn.net/qq_52914969?typeblog 本课程设计参考学习计算机网络 思科Cisco Packet Tracer仿真实验_哔哩哔哩_bilibili, 文章和pkg详见个人博客站: http://www.kervin24.to…

语义分割文献阅读——SETR:使用Transformer从序列到序列的角度重新思考语义分割

目录 摘要 Abstract 1 引言 2 Vision Transformer(ViT) 2.1 图片预处理&#xff1a;分块和降维 2.2 Patch Embedding 2.3 位置编码 2.4 Transformer Encoder的前向过程 3 SETR 3.1 图像序列化处理 3.2 Transformer 3.3 解码器 总结 摘要 本周阅读的论文题目是《R…

Mac上搭建k8s环境——Minikube

1、在mac上安装Minikube可执行程序 brew cask install minikub 安装后使用minikube version命令查看版本 2、安装docker环境 brew install --cask --appdir/Applications docker #安装docker open -a Docker #启动docker 3、安装kubectl curl -LO https://storage.g…

5. 【.NET 8 实战--孢子记账--从单体到微服务--转向微服务】--微服务基础工具与技术--Nacos

一、什么是Nacos Nacos 是阿里巴巴开源的一款云原生应用基础设施&#xff0c;它旨在简化微服务架构中服务治理和配置管理的复杂性。通过 Nacos&#xff0c;服务在启动时可以自动注册&#xff0c;而其他服务则可以通过名称来查找并访问这些注册好的实例。同时&#xff0c;Nacos…

【后端开发】系统设计101——Devops,Git与CICD,云服务与云原生,Linux,安全性,案例研究(30张图详解)

【后端开发】系统设计101——Devops&#xff0c;Git与CICD&#xff0c;云服务与云原生&#xff0c;Linux&#xff0c;安全性&#xff0c;案例研究&#xff08;30张图详解&#xff09; 文章目录 1、DevopsDevOps与SRE与平台工程的区别是什么&#xff1f;什么是k8s&#xff08;Ku…