1.任务目标
本任务承接 Task02 文本词频统计项目,属于NLP自然语言预处理基础核心任务 。在原有文本读取、清洗、词频统计的基础上,新增停用词过滤功能,剔除无实际语义的高频虚词,筛选出有实际意义的核心高频词汇,实现英文文本精细化词频分析。
2.步骤
步骤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
- count_words():遍历过滤后的单词,统计词频生成精准词频字典;
python
# 词频统计函数
def count_words(words):
counts = {}
for w in words:
# 单词存在则+1,不存在则初始化为0再+1
counts[w] = counts.get(w,0)+1
return counts
- 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() 的作用是什么?
将字典中所有键值对提取出来,转换为可排序、可遍历的列表结构,解决字典无法排序的问题。