查找文本中出现频率最高的单词

前言:借助|管道来执行多条语句

Find2More.sh脚本代码为:

#!/bin/bash
end=$1   #$1第一参数,出现频率最高的单词的前几项
cat $2 | #$2第二参数,目标文件
 tr -cs "[a-z][A-Z]" "[\012*]" | #将文本文件该一行一个单词的形式呈现
  tr A-Z a-z | #对单词中的大写转换为小写
   sort | #对单词进行排序              
    uniq -c | #对单词的重复进行统计
     sort -k1nr -k2 | #按频率排序,再按字母排序
       head -n"$end" #显示前几项

执行linux命令:

chmod u+x Find2More.sh #在root状态下添加执行权限

#执行Find2More.sh脚本,在filename文本中查找出现频率最高的单词的前5项

./Find2More.sh  5 filename

转载于:https://my.oschina.net/u/3378039/blog/1785540

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这里是一个简单的C语言代码示例,演示如何找到文本频率靠前的单词: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> // 定义结构体来储存单词及其出现频率 struct word { char *str; int count; }; void add_word(struct word **words, int *size, char *str) { // 如果单词已经在结构体数组里,增加其计数 for (int i = 0; i < *size; i++) { if (strcmp(str, words[i]->str) == 0) { words[i]->count++; return; } } // 否则,分配内存存储新的单词 struct word *new_word = malloc(sizeof(struct word)); new_word->str = strdup(str); new_word->count = 1; // 将新的单词添加到结构体数组 *size += 1; *words = realloc(*words, (*size) * sizeof(struct word)); (*words)[*size-1] = new_word; } int compare_words(const void *a, const void *b) { // 比较两个单词的计数 struct word *word_a = *(struct word **)a; struct word *word_b = *(struct word **)b; return word_b->count - word_a->count; } void free_words(struct word **words, int size) { // 释放内存 for (int i = 0; i < size; i++) { free((*words)[i].str); free(*words[i]); } free(*words); } int main() { char *input = "This is a sample sentence to test this simple code"; char *token = strtok(input, " "); struct word *words = NULL; int word_count = 0; // 将每个单词添加到结构体数组 while (token != NULL) { char *lower_token = strdup(token); for (int i = 0; lower_token[i]; i++) { lower_token[i] = tolower(lower_token[i]); } add_word(&words, &word_count, lower_token); token = strtok(NULL, " "); } // 按照单词计数排序 qsort(words, word_count, sizeof(struct word*), compare_words); // 打印前10个出现最频繁的单词及其计数 for (int i = 0; i < 10; i++) { printf("%s: %d\n", words[i]->str, words[i]->count); } // 释放内存 free_words(&words, word_count); return 0; } ``` 在上面的代码示例,我们使用了动态内存分配来储存每个单词及其出现次数,并使用 qsort() 函数按照单词计数排序。最后,我们打印前十个出现最频繁的单词及其计数,并释放整个结构体数组的内存。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值