统计出现次数最多的前3个ip及其次数(有一个文件ip.txt,每行一条ip记录,共若干行)

查看ip.txt

Linux sort命令用于将文本文件内容加以排序。

sort可针对文本文件的内容,以行为单位来排序。

-n 依照数值的大小排序。

-r 以相反的顺序来排序。

Linux uniq 命令用于检查及删除文本文件中重复出现的行列,一般与 sort 命令结合使用。

uniq 可检查文本文件中重复出现的行列。

-c或--count 在每列旁边显示该行重复出现的次数。

根据重复数量排序

head 命令可用于查看文件的开头部分的内容,有一个常用的参数 -n 用于显示行数,默认为 10,即显示 10 行的内容。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #define MAX_WORD_LEN 100 // 最大单词长度 #define TOP_N 10 // N个出现次数最多的单词 // 单词结构体 typedef struct { char word[MAX_WORD_LEN]; // 单词 int count; // 出现次数 } Word; // 比较函数,用于qsort排序 int cmp(const void *a, const void *b) { return ((Word *)b)->count - ((Word *)a)->count;} int main() { char filename[100]; // 文件名 printf("请输入文件名:"); scanf("%s", filename); FILE *fp = fopen(filename, "r"); // 打开文件 if (fp == NULL) { printf("文件打开失败!\n"); return 0; } Word *words = (Word *)malloc(sizeof(Word) * 1000); // 动态分配内存 int wordCount = 0; // 单词数量 char word[MAX_WORD_LEN]; // 临时存储单词 int len = 0; // 单词长度 char c; // 临时存储字符 while ((c = fgetc(fp)) != EOF) { // 逐个字符读取文件 if (isalpha(c)) { // 如果是字母 if (len < MAX_WORD_LEN - 1) { // 如果单词长度未超过最大长度 word[len++] = tolower(c); // 转换为小写字母并存储 } } else if (len > 0) { // 如果不是字母且单词长度大于0 word[len] = '\0'; // 添加字符串结束符 int i; for (i = 0; i < wordCount; i++) { // 查找单词是否已存在 if (strcmp(words[i].word, word) == 0) { // 如果已存在 words[i].count++; // 出现次数加1 break; } } if (i == wordCount) { // 如果不存在 strcpy(words[wordCount].word, word); // 存储单词 words[wordCount].count = 1; // 出现次数为1 wordCount++; // 单词数量加1 } len = 0; // 重置单词长度 } } fclose(fp); // 关闭文件 qsort(words, wordCount, sizeof(Word), cmp); // 按出现次数排序 printf("出现次数%d的单词:\n", TOP_N); int i; for (i = 0; i < TOP_N && i < wordCount; i++) { // 输出N个单词 printf("%s\t%d\n", words[i].word, words[i].count); } free(words); // 释放内存 return 0; } ``` --相关问题--: 1. 如何统计一个中文文本文件出现次数最多十个汉字

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

沐月浅歌

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

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

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

打赏作者

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

抵扣说明:

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

余额充值