编写程序统计一个英文文本文件中每个单词的出现次数

文章介绍了如何使用Python、C和C++三种编程语言实现统计英文文本文件中每个单词的出现次数,包括文件读取、正则表达式处理、词频统计和排序输出的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

题目简述

代码编写

Python代码实现

C语言代码实现

C++代码实现


题目简述


【问题描述】 编写程序统计一个英文文本文件中每个单词的出现次数(词频统计),并将统计结果按单词字典序输出到屏幕上。 注:在此单词为仅由字母组成的字符序列。包含大写字母的单词应将大写字母转换为小写字母后统计。

【输入形式】 打开当前目录下文件“article.txt”,从中读取英文单词进行词频统计。

【输出形式】 程序将单词统计结果按单词字典序输出到屏幕上,每行输出一个单词及其出现次数,单词和其出现次数间由一个空格分隔,出现次数后无空格, 直接为回车。

【样例输入】 当前目录下文件article.txt内容如下: “Do not take to heart every thing you hear."“Do not spend all that you have." “Do not sleep as long as you want,”

【样例输出】

all 1

as 2

do 3

every 1

have 1

……

代码编写


Python代码实现

import re

def word_count(file_path):
    # 创建一个空字典以存储单词频率
    word_dict = {}

    # 打开文件并逐行读取
    with open(file_path, 'r', encoding='utf-8') as file:
        # 遍历文件中的每一行
        for line in file:
            # 使用正则表达式在行中查找所有单词(忽略大小写)
            words = re.findall(r'\b\w+\b', line.lower())
            
            # 遍历每个单词并在字典中更新单词频率
            for word in words:
                word_dict[word] = word_dict.get(word, 0) + 1

    # 按字典序对单词字典进行排序
    s
编写一个C语言程序来统计文本文件每个单词出现的次数,可以分为以下几个步骤: 1. 打开文件:首先需要打开指定的文本文件,通常使用`fopen()`函数。 ```c #include <stdio.h> FILE *file = fopen("filename.txt", "r"); if (file == NULL) { printf("Failed to open file.\n"); return; } ``` 2. 读取文件内容:通过`fgets()`逐行读取文件内容,将每行分割成单词数组。 ```c char line[1000]; while (fgets(line, sizeof(line), file)) { // 分割单词 char *word = strtok(line, " "); while (word != NULL) { // 统计单词 // ... word = strtok(NULL, " "); } } ``` 3. 计数和存储:创建一个结构体或哈希表来保存每个单词及其对应的计数。这里我们可以使用`struct WordCount` 或者 `std::map<char*, int>` 来记录。 ```c #include <ctype.h> // 对于tolower() 函数 typedef struct { char* word; int count; } WordCount; WordCount word_counts[MAX_WORDS]; // 根据实际需求设置MAX_WORDS大小 int count_index = 0; // 更新计数 void update_count(char* word) { word = tolower(word); // 转换为小写便于比较 for (int i = 0; i < count_index; i++) { if (!strcmp(word, word_counts[i].word)) { word_counts[i].count++; break; } } if (i == count_index) { word_counts[count_index].word = strdup(word); word_counts[count_index].count = 1; count_index++; } } ``` 4. 关闭文件:完成所有处理后,记得关闭文件。 ```c fclose(file); ``` 5. 输出结果:遍历结构体,打印每个单词及其出现次数。 ```c for (int i = 0; i < count_index; i++) { printf("%s: %d\n", word_counts[i].word, word_counts[i].count); } ``` 完整的代码示例如下: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_WORDS 1000 ... void main() { // 省略打开、读取文件和更新计数部分... // 输出结果 for (int i = 0; i < count_index; i++) { printf("%s: %d\n", word_counts[i].word, word_counts[i].count); } // 省略关闭文件部分... } ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

会做饭的网络工程师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值