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() 的作用是什么?

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

相关推荐
小小龙学IT8 小时前
Python Polars 高性能数据处理引擎深度解析
开发语言·python·rust·1024程序员节
Nuanyt8 小时前
Hot 100 刷题笔记 · 数组与哈希专题(3 题)
java·笔记·算法·leetcode·哈希算法·1024程序员节
csdn_aspnet8 小时前
JavaScript 未排序数组中第 k 个最小/最大元素 (预期线性时间)
python
quantdash_cc8 小时前
如何利用标的信息为研究股票池补充名称和交易所信息?
开发语言·python·pandas·量化交易·1024程序员节·股票数据·quantdash
数字化转型分享点滴8 小时前
机加工企业上大数据分析系统有哪些容易踩的坑?
python·1024程序员节
B2_Proxy8 小时前
Scrapy 代理 IP 调度进阶:基于 Redis 与中间件的高可用架构实战
python·scrapy·1024程序员节
在世修行8 小时前
智学文枢:AI 客户端封装
python·http·ai·1024程序员节·pyside
破芽9 小时前
learn-claude-code-s08-s09-学习笔记
笔记·学习
言乐69 小时前
Python实现三轴联动根据数据自动打磨镜片模型
开发语言·python
星恒随风9 小时前
Linux网络编程基础(二):彻底理解局域网通信、MAC与IP地址、数据封装、端口号、网络字节序及Socket接口
linux·网络·笔记·学习·tcp/ip·1024程序员节