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) # 验证
相关推荐
刘马想放假1 小时前
CANviz 使用指南|Linux 安装、DBC 解码、实时曲线与 J1939 实战
linux·python·websocket
2601_967987372 小时前
python判断变量名不要调用任何函数实现
python·函数·语法·判断·变量名
卷无止境3 小时前
SALib敏感性分析的python库学习笔记
后端·python
柳鲲鹏4 小时前
内斗学概论:43、平级内斗
笔记
duansamve4 小时前
Python3+Flask+PostgreSQL18+Vue3项目生产环境用docker如何部署?
python·docker·flask
特立独行的猫A4 小时前
少 3 个环节、少 1 次 ABI、少 3500 行代码:cj-tauri 与 Ionic/Capacitor 的鸿蒙桥接机制对比
java·后端·python
特立独行的猫A4 小时前
cj-tauri vs Rust/Tauri 同款播放器实测:编译 21 秒 vs 11 分钟,磁盘 12 MB vs 1.2 GB
java·后端·python
duansamve5 小时前
详解Flask中Session和Cookie
python·flask
威哥爱编程6 小时前
模拟面试智能体开发实战 04:面试聊到哪算哪?用状态机把整场面试编排起来
python·agent·harmonyos
威哥爱编程6 小时前
模拟面试智能体开发实战 03:AI 面试官太客气?人设 Prompt 让它像个真考官
python·agent·harmonyos