03停用词过滤

1.任务目标

本任务承接 Task02 文本词频统计项目,属于NLP自然语言预处理基础核心任务 。在原有文本读取、清洗、词频统计的基础上,新增停用词过滤功能,剔除无实际语义的高频虚词,筛选出有实际意义的核心高频词汇,实现英文文本精细化词频分析。

2.步骤

步骤1:新增核心功能函数

  1. filter_stopwords():接收单词列表与停用词集合,过滤所有停用词,输出纯实词列表;
python 复制代码
# 停用词过滤
def filter_stopwords(words, stop_set):
    # 定义空列表,存储过滤后的有效单词
    filtered = []
    # 遍历所有单词,只保留非停用词
    for word in words:
        if word not in stop_set:
            filtered.append(word)
    return filtered
  1. count_words():遍历过滤后的单词,统计词频生成精准词频字典;
python 复制代码
# 词频统计函数
def count_words(words):
    counts = {}
    for w in words:
        # 单词存在则+1,不存在则初始化为0再+1
        counts[w] = counts.get(w,0)+1
    return counts
  1. get_top_n():对词频字典降序排序,提取指定数量的高频核心词汇。
python 复制代码
# 提取TopN高频词并降序排序
def get_top_n(count_dict, n):
    # 按词频数值降序排序
    sorted_items = sorted(count_dict.items(), key=lambda x:x[1], reverse=True)
    # 截取前n个高频词
    return sorted_items[:n]

步骤2:复用

python 复制代码
# 读取本地文本文件函数
def read_file(filename):
    # 以utf-8编码打开文件,避免乱码,with自动关闭文件,更安全
    with open(filename, encoding = "utf-8") as f:
        return f.read()

# 文本清洗、转小写、去标点、切割单词
def clean_split(text):
    # 归一化
    text_lower = text.lower()
    # 去标点
    text_clean = ""
    for ch in text_lower:
        if ch not in string.punctuation:
            text_clean += ch
    # 切割
    words = text_clean.split()
    return words

步骤3:编写主程序流水线

python 复制代码
if __name__ == "__main__":
    # 定义英文通用停用词集合(set查询效率O(1))
    stop_words = {"the","a","an","is","are","of","in","on","at","to","and","or","but","as","that","this"}
    # 1.读取文本
    content = read_file("article.txt")
    # 2.清洗文本、切割单词
    word_list = clean_split(content)
    # 3.过滤停用词,得到有效实词列表
    filtered_words = filter_stopwords(word_list, stop_words)
    # 4.统计精准词频
    word_counts = count_words(filtered_words)
    # 5.获取Top10高频核心词汇
    top_10 = get_top_n(word_counts,10)
    # 6.打印结果
    print("过滤停用词后的Top10高频实词:")
    for word, cnt in top_10:
        print(f"{word}: {cnt}次")

3.总结

1、停用词集合为什么用 set 而非 list?

list 查询时间复杂度 O(n),遍历效率低;set 基于哈希表,成员查询 O(1),速度极快,适合大规模文本过滤。

2、列表和字典的核心区别?

列表是有序容器,通过下标取值,支持排序切片;字典是键值对容器,通过 key 取值,无序、不能排序、不能切片。

3、items() 的作用是什么?

将字典中所有键值对提取出来,转换为可排序、可遍历的列表结构,解决字典无法排序的问题。

相关推荐
李可以量化2 小时前
Tornado 部署公域网络安全与防护(上)
python
风跟我说过她2 小时前
SQL 一键转经典 Chen 风格 ER 图:开源 CLI + 在线工具 + Agent Skill
数据库·python·sql·开源·开源软件
Ulyanov2 小时前
AudioVision Pro:基于 PySide6 + sounddevice 的实时音频可视化播放器设计
python·算法·音视频
ID34610744202 小时前
【课程设计】基于Spring Boot+Vue的校园共享无人机服务系统设计与实现-计算机毕设 附源码44219
javascript·vue.js·spring boot·python·node.js·php·课程设计
星空2 小时前
pycharm复习
ide·python·pycharm
Maiko Star2 小时前
Python 包与项目管理工具——uv
python·uv
秦哈哈2 小时前
【Hello Agents】学习笔记(二)
笔记·学习·microsoft
weixin199701080163 小时前
[特殊字符]《京东POP二手品类对接:B2C订单模型 vs 二手C2C属性的字段转换难题》(附Python源码)
前端·python·算法
承渊政道3 小时前
Python IDLE鸿蒙PC适配全记录:从Tkinter桌面程序到ArkUI原生开发闭环
开发语言·python·harmonyos·鸿蒙系统·桌面程序