1.任务目标
读一篇考研英语真题 文章,忽略大小写和标点,统计每个单词出现次数,输出前10个高频词及次数。
2.步骤
-
准备语料 :找一篇考研英语阅读真题原文,存成 article.txt,与代码同目录。存文件时编码选 UTF-8
task01_wordcount/ ├─ wordcount.py └─ article.txt -
读取文件:用 open() 读入全文;先 print 出来确认读到了原文,再往下走
python# 读取文章 f = open("article.txt", encoding = "utf-8") # 读取文件 text = f.read() # 把 f 里的内容读出来,存进变量 text print(text) # 把 text 打印到终端 -
清洗 + 切词:
-
转小写 lower()
pythontext_lower = text.lower() # 将所有单词转成小写,并存进text_lower print(text_lower) # 验证 -
去标点,利用string.punctuation
pythontext_clean = "" for ch in text_lower: if ch not in string.punctuation: text_clean += ch print (text_clean) # 验证 -
split() 成单词列表
python# 第四步 将单词切分放入列表 words = text_clean.split() # 切割成单词,返回列表words print(words) # 验证
-
-
统计词频:
pythoncounts = {} for word in words: if word in counts: # 这个单词已经见过了 counts[word] += 1 else: # 头一次见 counts[word] = 1 print(counts) #验证 -
排序取前10:
pythontop_10 = sorted(counts.items(), key = lambda item : item[1], reverse = True) [:10] print(top_10) # 验证