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) # 验证
相关推荐
Source.Liu23 分钟前
【A11】服务器数据库结构笔记
服务器·数据库·笔记
2601_9628857235 分钟前
从 baostock 迁移到 AlphaFeed:接口对照与代码迁移指南
python
AI情绪识别开源1 小时前
检信ALLEMOTION 标定治理与信号质量闸门 · 老年无感认知评估分析器
python
1314lay_10071 小时前
ABAP 读取服务器的文件 OPEN DATASET,READ DATASET f_filepath INTO l_file.
经验分享·笔记
七夜zippoe1 小时前
启元 Q1 腿部运动学逆解:Python 算站立下蹲关节角
开发语言·python·ai·机器人·腿部运动学
MichaelJohn1 小时前
我用 Obsidian + Claude Code + GitHub 搭了个真正「会生长」的第二大脑
笔记
第404号工位1 小时前
插上充电宝真能偷光相册?我拆解了一台改装充电宝,实测“恶意充电”的真实攻击链
linux·python·架构
技术卷2 小时前
Windows 下自定义 MCP 踩坑:stdin 默认继承导致 CPython 启动阻塞
python·mcp·zcode
小oo呆2 小时前
【学习心得】Python多进程
python·操作系统
CodeGL2 小时前
9、Python基础之IO编程
开发语言·数据库·python