请读入句子,统计句子中每个单词出现的次数问题

本文介绍了一种使用C++编程语言统计文本中各单词出现次数,并按首字母顺序进行排序的方法。通过替换非字母字符并利用标准模板库(STL)的功能实现了这一功能。

原帖见: 

http://community.youkuaiyun.com/Expert/TopicView3.asp?id=5023839

题目:

输出每个单词出现的次数
比如:aaa,bbb,ccc,aaa,avc,aaa.
那么aaa为3,bbb为1.....
在输出时,还要将输入单词按首字母排列

解答:

     回复人:du51(郁郁思扬) ( 两星(中级)) 信誉:100     2006-9-15 15:10:45     得分:0

/*------------------------------------*/
#include
< iostream >
#include
< string >
#include
< vector >
#include
< sstream >
#include
< algorithm >
#include
< functional >
#include
< cctype >
#include
< iterator >
using   namespace  std;
int  main()
{
string test="aaa,bbb,ccc,aaa,avc,aaa.ccc wwwww www.youkuaiyun.com www.warcraft.com";
replace_if(test.begin(),test.end(),not1(ptr_fun(::isalpha)),
' ');
istringstream ss(test);
vector
<string> vec;
copy(istream_iterator
<string>(ss),istream_iterator<string>(),back_inserter(vec));
sort(vec.begin(),vec.end());
for(vector<string>::iterator it=vec.begin(),start=vec.begin();it!=vec.end();start=it)
{
if((it=adjacent_find(start,vec.end(),not_equal_to<string>()))!=vec.end())++it;
cout
<<*start<<" "<<distance(start,it)<<endl;
}

system(
"PAUSE");
return 0;
}
你可以通过以下步骤来统计文件中每个单词出现的次数: 1. 读取文件:使用Java的文件读取功能,将待统计的文件读入内存中。 2. 分离单词:将读入的文件内容按照空格、标点符号等分离成单词,可以使用Java的正则表达式来实现。 3. 统计单词数量:使用HashMap来存储每个单词出现的次数,遍历每个单词,如果该单词已经在HashMap中存在,则将其出现次数加1,否则将该单词加入HashMap,并将其出现次数设为1。 4. 输出结果:遍历HashMap,输出每个单词及其出现次数。 以下是示例代码: ```java import java.io.BufferedReader; import java.io.FileReader; import java.util.HashMap; import java.util.Map; public class WordCount { public static void main(String[] args) { String filename = "test.txt"; // 待统计的文件名 Map<String, Integer> wordCount = new HashMap<>(); // 用于存储单词出现次数的HashMap // 读取文件 try (BufferedReader reader = new BufferedReader(new FileReader(filename))) { String line; while ((line = reader.readLine()) != null) { // 分离单词 String[] words = line.split("[\\p{Punct}\\s]+"); for (String word : words) { // 统计单词数量 if (wordCount.containsKey(word)) { wordCount.put(word, wordCount.get(word) + 1); } else { wordCount.put(word, 1); } } } } catch (Exception e) { e.printStackTrace(); } // 输出结果 for (Map.Entry<String, Integer> entry : wordCount.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } } ``` 这个示例代码可以读取名为test.txt的文件,统计其中每个单词出现的次数,并输出结果。你可以将其修改成符合你自己需求的代码。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值