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

问题1:查找文本中n个出现频率最高的单词

#!/bin/bash
end=$1   #S1是输出频率最高单词的个数
cat $2 |  #是目标文本文件的名称
tr -cs "[a-z][A-Z]" "[\n*]" |  #将文本文件以一行一个单词的形式显示
tr A-Z a-z | #将单词的大写字母转为小写字母
sort | #对单词排序
uniq -c | #对排序好的单词列表统计每一个单词出现的次数
sort -k1nr -k2 | #按出现频率排序,再按字母顺序排序
head -n "$end" #显示前$end行 如何$end = 5则显示先5行

假如脚本名为run.sh 单词文本文件名为words 想找出5个出现频率最高的单词及次数

./run.sh 5 words

1。将文件text中的单词,不是英文单词的都去掉,保留的每一个单词作为一行显示。

cat text | tr -cs "[a-z][A-Z]" "[\n*]"

这里写图片描述
2。uniq 去掉相邻重复的行,uniq -c 可以统计每一个行出现的次数, 一般和sort结合使用。

3。显示文本text前5行.

cat text | head -n 5

问题2: 将一个text文件中的单词”xyz”替换为另一个单词”abc”并写入newfile文本文件。

cat text | tr "xyz" "abc" > newfile
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
这里是一个简单的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() 函数按照单词计数排序。最后,我们打印前十个出现最频繁的单词及其计数,并释放整个结构体数组的内存。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值