统计字符串中每个单词出现的个数和频率----四种方法

’’***'统计每个单词出现的个数(三种方法*
第一种如下:(最简单的方式**)**
‘’’**

sentance = 'I can because i think i can '
#切片分隔成列表序列,用列表推导式表达
rresult = {word: sentance.split ().count ( word ) for word in set ( sentance.split () )}
print ( rresult )
print ( (sentance.split ()) )

统计每个单词出现的个数(第二种)–字典方法(也是比较常见的一种方式)

def word_amount(sentance):
    split_str = sentance.split ()
    dict_new = {}.fromkeys ( split_str, 0 )
    for word_name in split_str:
        if word_name not in dict_new.keys ():
            dict_new[word_name] = 1
            print ( '1' )
    else:
        dict_new[word_name] += 1
return dict_new


if __name__ == "__main__":
    sentance = ' i think i can and can do well'
    print ( word_amount ( sentance ) )

第三种方法:****(引用模块,学会使用一些常见的模块)

from collections import Counter

str0 = 'I can because i think i can'
counts = Counter ( str0.split () )
print ( counts )

还有第四种方法,就是__len__ 和__getitem__,(置字典方法和魔术方法的结合)较难,不推荐,以后深造的时候可以多学学

class Countlist:
    def __init__(self,*args):
        self.values = [a for a  in args]
        self.count ={}.fromkeys(range(len(self.values)),0)
    def __len__(self):
        return len(self.values)
    def __getitem__(self, a):
        self.count[a] += 1
        return self.values[a]


c1 = Countlist(1,3,3,5,7,9)
c2 = Countlist(2,4,6,8,10)
c1[2]
c1[3] + c1[2]
print(c1.values[2])
print(c1.count)
print(c1.values)

结束

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在C语言实现7-4题,即词频统计,可以通过使用哈希表的方式来解决。哈希表是根据关键字直接访问存储位置的数据结构,它通过计算关键字的哈希值,将其映射到某个数组或链表的位置,实现高效的查找和插入操作。 具体实现步骤如下: 1. 定义一个哈希表,作为存储词频的数据结构。可以使用数组和链表的结合来实现,每个数组元素存储一个链表。 2. 读取输入的字符串。 3. 遍历字符串,依次将每个单词提取出来。可以通过空格或标点符号来分隔单词。 4. 对每个单词进行哈希计算,得到哈希值。 5. 在哈希表查找对应哈希值的位置,如果已存在则更新词频,否则插入新的节点。 6. 输出哈希表每个单词的词频。 以下是一个简单的示例代码: ``` #include <stdio.h> #include <string.h> #include <ctype.h> // 哈希表节点 typedef struct Node { char word[100]; // 单词 int frequency; // 词频 struct Node* next; // 链表指针 } Node; #define HASH_SIZE 1000 // 哈希表大小 Node* hashTable[HASH_SIZE]; // 哈希表数组 // 计算哈希值 int hash(char* word) { int sum = 0; for (int i = 0; i < strlen(word); i++) { sum += word[i]; } return sum % HASH_SIZE; } // 在哈希表插入或更新节点 void insertOrUpdate(char* word) { int index = hash(word); Node* node = hashTable[index]; while (node != NULL) { if (strcmp(node->word, word) == 0) { // 单词已存在,更新词频 node->frequency++; return; } node = node->next; } // 单词不存在,插入新节点 Node* newNode = (Node*) malloc(sizeof(Node)); strcpy(newNode->word, word); newNode->frequency = 1; newNode->next = hashTable[index]; hashTable[index] = newNode; } // 输出哈希表单词和词频 void printFreq() { for (int i = 0; i < HASH_SIZE; i++) { Node* node = hashTable[i]; while (node != NULL) { printf("%s: %d\n", node->word, node->frequency); node = node->next; } } } int main() { // 初始化哈希表 memset(hashTable, 0, sizeof(hashTable)); char input[10000]; scanf("%[^\n]", input); // 读取输入的字符串直到换行符 char* token = strtok(input, " ,.-"); // 使用空格和标点符号分隔单词 while (token != NULL) { for (int i = 0; i < strlen(token); i++) { token[i] = tolower(token[i]); // 统一转为小写字母 } insertOrUpdate(token); token = strtok(NULL, " ,.-"); } // 输出词频 printFreq(); return 0; } ``` 这样,输入一段文本,程序会输出每个单词的词频。注意,此代码只是一个简单示例,没有考虑一些特殊情况,如单词超长等,需根据实际需求进行调整和完善。 ### 回答2: 题目要求使用C语言编写一个程序,统计一个给定字符串各个单词出现次数。下面是一个简单的C语言代码示例: ```c #include <stdio.h> #include <string.h> void wordFrequency(char *str) { int len = strlen(str); int count = 1; for (int i = 0; i < len; i++) { if (str[i] == ' ') { count++; continue; } while (str[i] != ' ' && i < len) { i++; } } printf("单词个数:%d\n", count); } int main() { char str[100]; printf("请输入字符串:"); gets(str); wordFrequency(str); return 0; } ``` 代码的wordFrequency函数用于统计单词个数。它首先通过strlen函数获取字符串的长度,然后使用一个循环遍历字符串。在循环,每次遇到空格符就将计数器加一,忽略其他符号。最后输出计数器的值,即为单词个数。 在主函数,我们使用gets函数获取用户输入的字符串,并调用wordFrequency函数进行统计。最后输出结果。注意,由于使用了gets函数,输入的字符串长度不能超过100个字符。 这是一个简单的单词频率统计程序,只能统计单词个数,并不考虑重复出现的情况。如果需要统计每个单词的具体出现次数,需要对代码进行进一步的修改和完善。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值