01词频统计器

1.任务目标

读一篇考研英语真题 文章,忽略大小写和标点,统计每个单词出现次数,输出前10个高频词及次数

2.步骤

  1. 准备语料 :找一篇考研英语阅读真题原文,存成 article.txt,与代码同目录。存文件时编码选 UTF-8

    复制代码
    task01_wordcount/
    ├─ wordcount.py      
    └─ article.txt      
  2. 读取文件:用 open() 读入全文;先 print 出来确认读到了原文,再往下走

    python 复制代码
    # 读取文章
    f = open("article.txt", encoding = "utf-8") # 读取文件
    text = f.read()         # 把 f 里的内容读出来,存进变量 text
    print(text)           # 把 text 打印到终端
  3. 清洗 + 切词

    1. 转小写 lower()

      python 复制代码
      text_lower = text.lower() # 将所有单词转成小写,并存进text_lower
      print(text_lower) # 验证
    2. 去标点,利用string.punctuation

      python 复制代码
      text_clean = ""
      for ch in text_lower:
          if ch not in string.punctuation:
              text_clean += ch
      print (text_clean) # 验证
    3. split() 成单词列表

      python 复制代码
      # 第四步 将单词切分放入列表
      words = text_clean.split() # 切割成单词,返回列表words
      print(words) # 验证
  4. 统计词频

    python 复制代码
    counts = {}
    for word in words:
        if word in counts:        # 这个单词已经见过了
            counts[word] += 1
        else:                     # 头一次见
            counts[word] = 1
    print(counts) #验证
  5. 排序取前10

    python 复制代码
    top_10 = sorted(counts.items(), key = lambda item : item[1], reverse = True) [:10]
    print(top_10) # 验证
相关推荐
今天AI了吗1 小时前
去中心化 AI 反馈系统:数据不上链,凭证与激励分开管
人工智能·windows·python·数据分析·去中心化·区块链·embedding
浔溺1 小时前
al+大数据每日学习笔记37
大数据·笔记·学习
今朝唯我少年郎1 小时前
Codex安全盲区代码漏洞生成实测
python·程序员
E_ICEBLUE1 小时前
Python 实现 Excel 转 Markdown,支持工作表、单元格区域和批量处理
python·excel·markdown·格式转换
TheBestRucy1 小时前
PyTorch 基本使用学习笔记
pytorch·笔记·学习
志尊宝1 小时前
Vue3 零基础每日笔记(016):v-for 列表渲染——key 的作用与为什么不能用 index
javascript·vue.js·笔记
ouynagda1 小时前
51 单片机 LED 流水灯 + 数码管动态扫描学习笔记(STC89C52)
笔记·单片机·学习
ctlover1 小时前
Python高级与正则表达式
开发语言·python