统计单词个数

题目大意:输入一个字符串,求它包含多少个单词。单词间以一个或者多个空格分开。第一个单词前,最后一个单词后也可能有0到多个空格。

AC代码:

#include<stdio.h>
int get_word_num(char *buf)
{
	int n=0;
	int  tag=1;
	char *p=buf;
	for(;*p!=0&&*p!=13&&*p!=10;p++)
	{
		if(*p==' '&&tag==0)	
			tag=1;
		if(*p!=' '&&tag==1)
		{
			n++;
			tag=0;
		}
	}
	return n;
}
int main()
{
	char buf[1000];
	fgets(buf,1000,stdin);
	printf("%\n",get_word_num(buf));
	return 0;
 } 

### 实现Python统计单词个数的功能 在Python中,可以通过多种方式实现统计单词个数的功能。以下是一个完整的解决方案,涵盖了字符串处理、分割以及字典的应用。 #### 方法一:使用基础字符串操作和字典 可以利用字符串的 `split()` 方法将句子分割为单词列表,并通过字典统计每个单词出现的次[^3]。 ```python def count_words(text): # 将文本转换为小写并移除标点符号 for char in ",.;:?!" : text = text.replace(char, " ") # 分割字符串为单词列表 words = text.lower().split() word_dict = {} for word in words: if word in word_dict: word_dict[word] += 1 else: word_dict[word] = 1 return word_dict # 示例 text = "Hello world! Hello Python. Python is great, and the world agrees." result = count_words(text) print("单词统计结果:", result) ``` #### 方法二:使用正则表达式 对于更复杂的字符串处理,可以使用 `re` 模块中的正则表达式来分割单词[^4]。 ```python import re def count_words_regex(text): # 使用正则表达式匹配单词 words = re.findall(r'\b\w+\b', text.lower()) word_dict = {} for word in words: if word in word_dict: word_dict[word] += 1 else: word_dict[word] = 1 return word_dict # 示例 text = "Hello world! Hello Python. Python is great, and the world agrees." result = count_words_regex(text) print("单词统计结果:", result) ``` #### 方法三:使用 `collections.Counter` Python 的 `collections` 模块提供了 `Counter` 类,能够简化单词统计过程[^2]。 ```python from collections import Counter import re def count_words_counter(text): # 使用正则表达式提取单词并转换为小写 words = re.findall(r'\b\w+\b', text.lower()) # 使用 Counter 统计单词频率 word_count = Counter(words) return dict(word_count) # 示例 text = "Hello world! Hello Python. Python is great, and the world agrees." result = count_words_counter(text) print("单词统计结果:", result) ``` 以上三种方法均能实现单词统计功能,但推荐使用 `Counter`,因为它代码简洁效率较高。 #### 注意事项 - 在处理文本时,需要先清理标点符号以确保统计准确性[^5]。 - 如果输入包含大小写混合的单词,则需统一转换为小写以避免重复统计。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值