当前位置: 首页 > news >正文

第2个小脚本:批量读取所有英文txt文章内容提取高频的单词

在这里插入图片描述
如何把网站的英文文章内容下载到txt文件,请看第3个小脚本:批量下载某网站的所有英文内容到txt。
在这里插入图片描述

在这里插入图片描述
代码如下:

#第二步:从当前目录读取txt文件,并统计高频单词
import os
import re
from collections import Counter

def read_txt(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        text = f.read()
    return text

def count_word(text):
    # 去除标点符号
    text = re.sub(r'[^\w\s]', '', text)
    # 转换成小写
    text = text.lower()
    # 切分成单词列表
    words = text.split()
    # 过滤掉不是英语单词的word
    words = [word for word in words if re.match(r'^[a-z]+$', word)]
    # 统计词频
    word_count = Counter(words)
    return word_count


if __name__ == '__main__':
    # 读取当前目录下所有的txt文件
    current_dir = os.getcwd()
    txt_files = [os.path.join(current_dir, file) for file in os.listdir(current_dir) if file.endswith('.txt')]
    # 遍历所有txt文件,统计词频
    word_count = Counter()
    for file_path in txt_files:
        text = read_txt(file_path)
        word_count += count_word(text)
    # 输出结果并保存到文件
    index = 0
    with open('high_frequency_words.txt', 'w', encoding='utf-8') as output_file:
        for word, count in word_count.most_common(5000):
            if 3 <= len(word) <= 15 and "__" not in word and count > 1:
                index += 1
                print(f"{index}. {word}: {count}")
                output_file.write(f"{word}\n")
    print('生成')



相关文章:

  • Matlab学习笔记五十:循环语句和条件语句的用法
  • 【微服务架构】SpringSecurity核心源码剖析+jwt+OAuth(七):SpringSecurity中的权限管理
  • 【HD-RK3576-PI】系统更新与恢复
  • Spring MVC 是如何将 @RequestMapping 注解映射到对应的 Handler 方法?
  • 【大英赛】大英赛准备笔记
  • MCP基础学习计划详细总结
  • Vue3项目中的前缀和
  • C++ ------ 智能指针
  • 2025年常见渗透测试面试题-webshell免杀思路(题目+回答)
  • 抓包神器,自研EtherCAT抓包工具
  • Next.js/Nuxt.js 服务端渲染优化
  • 1.1 初识AI
  • C语言进阶之字符函数和字符串函数
  • AcWing 5972. 科学记数法
  • 【游戏安全】强制交互类风险
  • Magnet 库的技术架构与核心机制解析
  • Docker部署SpringBoot项目(完整版)
  • 重载“<<”操作符
  • 基于多通道降压稳压器的机器人关节供电系统设计
  • 人工智能day03
  • 河南:响鼓重锤对违规吃喝问题露头就打、反复敲打、人人喊打
  • 欠债七十万后,一个乡镇驿站站长的中年心事
  • 30平米的无障碍酒吧里,我们将偏见折叠又摊开
  • 从能源装备向应急装备蓝海拓展,川润股份发布智能综合防灾应急仓
  • 马上评|“为偶像正名”的正确做法是什么
  • 阿尔巴尼亚执政党连续第四次赢得议会选举,反对党此前雇用特朗普竞选经理