用c++编程:统计一个英文文本编程文件中一个特定单词出现的次数,并将结果存入指定文件中!

当前访客身份:游客 [
当前位置:
发布于 日 16时,
(1)程序的输入文本为每行切词后的结果,每个单词(term)之间以制表符分割。
(2)使用hashmap计算单词和其出现的个数,key为term,value为其出现次数。统计完后将hashmap转换为vector,使用STL的标准排序算法。
代码片段(3)
1.&[代码][C/C++]代码&&&&
#include &iostream&
#include &string&
#include &fstream&
#include &vector&
#include &algorithm&
#include &ext/hash_map&
using namespace __gnu_
struct str_hash{
size_t operator()(const string& str) const
unsigned long __h = 0;
for (size_t i = 0 ; i & str.size() ; i ++)
__h = 5*__h + str[i];
return size_t(__h);
bool less_first(pair&int, string& const& lhs, pair&int, string& const& rhs)
return lhs.first & rhs.
vector&pair&int, string& & mirror_map(hash_map&string, int, str_hash& const& m)
vector&pair&int, string& &
for (hash_map&string, int, str_hash&::const_iterator i = m.begin(); i != m.end(); ++i)
mirror.push_back(pair&int, string&(i-&second, i-&first));
std::sort(mirror.begin(), mirror.end(), less_first);
int main()
input.open("word.txt");
output.open("wordfrequency.txt");
hash_map&string,int,str_hash&
while(getline(input,eachline) )
string::size_type start = 0;
string::size_type end = eachline.find_first_of("\t");
while(end != string::npos){
string term = eachline.substr(start, end - start);
termtime[term]++;
start = end + 1;
end = eachline.find_first_of("\t",start);
if(start != eachline.size()){
string term = eachline.substr(start);
termtime[term]++;
vector&pair&int, string& & mirror = mirror_map(termtime);
for(vector&pair&int, string& &::iterator myiter= mirror.begin(); myiter != mirror.end(); ++myiter){
output&&myiter-&second&&"\t"&&myiter-&first&&
input.close();
output.close();
cout && "Done" &&
system("pause");
2.&[代码]输入文本例子&&&&
你好 中国 请
今天 是个 好 天气 晴天 中国 大神
请 大神 指教
请 大神 指教
3.&[代码]输出&&&&
开源中国-程序员在线工具:
wordcount.让我想起了mapreduce。
2楼:intergret 发表于
引用来自“blur”的评论wordcount.让我想起了mapreduce。我现在在做的就是把一个文本切完词后,统计下各个term的频率,排下序。接着想把这个程序放到hadoop上跑跑,但目前还刚学hadoop,不知道您有什么建议~
3楼:blur 发表于
引用来自“intergret”的评论引用来自“blur”的评论wordcount.让我想起了mapreduce。我现在在做的就是把一个文本切完词后,统计下各个term的频率,排下序。接着想把这个程序放到hadoop上跑跑,但目前还刚学hadoop,不知道您有什么建议~hadoop是java的。
4楼:Fred 发表于
引用来自“blur”的评论wordcount.让我想起了mapreduce。hadoop的wordcount效率才不忍赌啊~
5楼:blur 发表于
引用来自“Fred”的评论引用来自“blur”的评论wordcount.让我想起了mapreduce。hadoop的wordcount效率才不忍赌啊~....你试过?
6楼:Fred 发表于
引用来自“blur”的评论引用来自“Fred”的评论引用来自“blur”的评论wordcount.让我想起了mapreduce。hadoop的wordcount效率才不忍赌啊~....你试过?不管单机还是clund都练习过~~分解和合成都要消耗一定的时间
7楼:blur 发表于
引用来自“Fred”的评论引用来自“blur”的评论引用来自“Fred”的评论引用来自“blur”的评论wordcount.让我想起了mapreduce。hadoop的wordcount效率才不忍赌啊~....你试过?不管单机还是clund都练习过~~分解和合成都要消耗一定的时间你的数据量太小了。试试更大的数据量。
8楼:intergret 发表于
引用来自“blur”的评论引用来自“Fred”的评论引用来自“blur”的评论引用来自“Fred”的评论引用来自“blur”的评论wordcount.让我想起了mapreduce。hadoop的wordcount效率才不忍赌啊~....你试过?不管单机还是clund都练习过~~分解和合成都要消耗一定的时间你的数据量太小了。试试更大的数据量。我今天跑了hadoop自带的例子wordcount,就一个小文本,速度是有点慢,大数据量下速度真的会很理想?
9楼:blur 发表于
引用来自“intergret”的评论引用来自“blur”的评论引用来自“Fred”的评论引用来自“blur”的评论引用来自“Fred”的评论引用来自“blur”的评论wordcount.让我想起了mapreduce。hadoop的wordcount效率才不忍赌啊~....你试过?不管单机还是clund都练习过~~分解和合成都要消耗一定的时间你的数据量太小了。试试更大的数据量。我今天跑了hadoop自带的例子wordcount,就一个小文本,速度是有点慢,大数据量下速度真的会很理想?有质疑的精神是好的,不过建议自己先动手试试。Hadoop的用户包括facebook、yahoo、google,国内的阿里。楼主的这个问题叫谷歌们情何以堪啊。
10楼:intergret 发表于
引用来自“blur”的评论引用来自“intergret”的评论引用来自“blur”的评论引用来自“Fred”的评论引用来自“blur”的评论引用来自“Fred”的评论引用来自“blur”的评论wordcount.让我想起了mapreduce。hadoop的wordcount效率才不忍赌啊~....你试过?不管单机还是clund都练习过~~分解和合成都要消耗一定的时间你的数据量太小了。试试更大的数据量。我今天跑了hadoop自带的例子wordcount,就一个小文本,速度是有点慢,大数据量下速度真的会很理想?有质疑的精神是好的,不过建议自己先动手试试。Hadoop的用户包括facebook、yahoo、google,国内的阿里。楼主的这个问题叫谷歌们情何以堪啊。呵呵,这个我当然知道。会好好看看hadoop的~
开源从代码分享开始
intergret的其它代码1 csapp第一次编程实验,读取文本文件统计单词出现次数 Windows Develop 240万源代码下载-
&文件名称: 1& & [
& & & & &&]
&&所属分类:
&&开发工具: C-C++
&&文件大小: 2 KB
&&上传时间:
&&下载次数: 0
&&提 供 者:
&详细说明:csapp第一次编程实验,读取文本文件统计单词出现次数-lab1 of the course csapp, counting the times of appearances of the words
文件列表(点击判断是否您需要的文件,如果是垃圾请在下面评价投诉):
&&assignment1__.cpp
&输入关键字,在本站240万海量源码库中尽情搜索:> 帮看看下面的题目五.编程题1.编程读取一段文本,统计其中包含多少个一个字母的单词,两个字母的单词,
帮看看下面的题目五.编程题1.编程读取一段文本,统计其中包含多少个一个字母的单词,两个字母的单词,
wangzhijie508 & &
发布时间: & &
浏览:6 & &
回复:2 & &
悬赏:0.0希赛币
帮看看下面的题目五.编程题1.编程读取一段文本,统计其中包含多少个一个字母的单词,两个字母的单词,等等(设文本中共只含单词,单词间用空格或标点符号分隔)2.从键盘输入一个字符串到字符数组中,然后逆序存放3.用公式s=1+x/1!+x^2/2!+x^3/3!+ ,-∞&x&∞,求s的值,其中x从键盘输入,直到1/n!小于0.000001为止4.打印如下钻石图形 &
*5.求&S=a0+a1x+a2& x^2+ .+anx^n,其中x,n,ai从键盘输入,要求ai用数组存放6.实现十进制到十六进制的转换-----------------------------------------第一题和第三题不会,
第一题看看行不  C/C++ code  #include &stdio.h&
#include &stdlib.h&
#include &string.h&
#define MAX_LEN 20
#define MAX_NUM 100
//*lenth[x].word[y]是单词长度为x的第y个单词
struct lenth
char *word[MAX_NUM];
//lenth[x].sum是长度为x的单词的总数
//lenth[x].num是长度为x的单词第num个
}lenth[MAX_LEN] = {{ {&&}, 0, 0} };
int main()
FILE *fp, *
char p[MAX_NUM];
//fp打开原文件word.txt读数据
if((fp = fopen(&word.txt&, &r&)) == NULL)
printf(&cannot open word.txt&);
//out打开out.txt写处理后的数据
if((out = fopen(&out.txt&, &w+&)) == NULL)
printf(&cannot open out.txt&);
while(!feof(fp))
temp = fgetc(fp);//一个一个第从word.txt中读字符
//将word.txt中出英文字母外的符号全换成逗号,(但'\'换不了...)
if (temp & 'A' || temp & 'z')
temp = ',';
fputc(temp, out);//一个一个地往out.txt中写word.txt中的字符(遇到非字母就换成逗号)
fclose(out);//写入完成
fclose(fp);//读出完成
if((fp = fopen(&out.txt&, &r&)) == NULL)//用fp来读out.txt
printf(&cannot open word.txt&);
//out.txt中没有空格,只有逗号分隔开的,所以整个out.txt的内容就是一个字符串
fscanf(fp, &%s&, p);//p就是out.txt的全部内容
q = strtok(p, &,&);//strtok可以根据用户所提供的分割符(同时分隔符也可以为复数比如“,。”)将一段字符串分割直到遇到&\0&.
i = strlen(q);//分割后字符串的长度
j = lenth[i].
lenth[i].word[j] =//将长度为i的第一个字符串保存到lenth[i].word[0]中,第二个长度为i的字符串保存在lenth[i].word[1]中...
q = strtok(NULL, &,&);
lenth[i].sum++;//长度为i的字符串的总数加1.
lenth[i].num++;
//输出,只输出lenth&0的字符串
for (i = 0; i & MAX_LEN; i++)
if (lenth[i].sum & 0)
printf(&lenth : %d\tsum : %d\n&, i, lenth[i].sum);
for (j = 0; j & lenth[i]. j++)
printf(&%s\t&, lenth[i].word[j]);
printf(&\n\n&);
fclose(fp);
wangzhiming & &
& & (0)(0)
第三题就是求e的x次方,那个公式就是e的x方的级数展开式:  C/C++ code  #include &stdio.h&
#include &stdlib.h&
#include &math.h&
int factorial(int n)
if(n == 0) return 1;
int result = 1;
for(int i = 1; i &= ++i)
int main(int argc, char** argv)
double s = 1.0;
int n = 1;
scanf(&%lf&, &x);
printf(&%f\n&, x);
while(factorial(n) & )
s += (pow(x, n) / (double)factorial(n));
printf(&%f\n&, s);
}wangzhilin & &
& & (0)(0)
本问题标题:
本问题地址:
温馨提示:本问题已经关闭,不能解答。
暂无合适的专家
&&&&&&&&&&&&&&&
希赛网 版权所有 & &&写一个程序,分析一个文本文件中各个单词出现的频率
在我们这学期开设的软件工程课上,老师布置了一道题。如下: 请实现程序:筛选出文章中出现频率最高的10个词语。文件大小30k--300k. 最近开始学习hadoop,(hadoop 以下简称hd)。 一看这题,我立马想到了hd去实现,这300k的数据简直不够塞牙缝,由于本人是新手,就在网上找资料,不料,都没有能完全满足要求的代码。 ps:本程序是在wordcount基础上修改的,并且用的是hd的老mapreduce框架。(mapreduce以下简称mapred) 大致思想是将多个mapred连接起来,将复杂任务分解成一些简单的子任务,每个均需通过单独的mapred作业来完成。 首先,按照mapred框架,在第一次完成mapred之后,每个单词出现的频率会被统计,并且成 键值对(key/value)形式(单词 /次数),reduce之后,单词会成升序进行排序。 由于mapred只会对键进行排序,所以我们下一步需要将键值互换位置,此时需要用到hd提供的api函数,InverseMapper.class。然后就会让单词按照出现次数升序排序,由于我们需要的是降序排序,所以需要实现一个降序排序的类(ps:此处参考了其他高手的解决方案)IntWritableDecreasingComparator 最后,再使用一个自定义map类,进行top-k的选取。附上完整代码 import java.io.IOE import java.util.R import java.util.StringT import org.apache.hadoop.conf.C import org.apache.hadoop.fs.FileS import org.apache.hadoop.fs.P import org.apache.hadoop.io.IntW import org.apache.hadoop.io.T import org.apache.hadoop.io.WritableC import org.apache.hadoop.mapreduce.J import org.apache.hadoop.mapreduce.M import org.apache.hadoop.mapreduce.R import org.apache.hadoop.mapreduce.Mapper.Cimport org.apache.hadoop.mapreduce.lib.input.FileInputF import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputF import org.apache.hadoop.mapreduce.lib.map.InverseM import org.apache.hadoop.mapreduce.lib.output.FileOutputF import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputF import org.apache.hadoop.util.GenericOptionsP public class WordCount2 {
public static class TokenizerMapper extends
Mapper&Object, Text, Text, IntWritable& {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(Object key, Text value, Context context)
throws IOException, InterruptedException {
String line = value.toString().toLowerCase(); // 全部转换为小写字母 StringTokenizer itr = new StringTokenizer(line, " \t\n\f\" . , : ; ? ! [ ] ' - "); while (itr.hasMoreTokens()) {
word.set(itr.nextToken());
context.write(word, one);
//top-k maper public static class TokenizerMapper2
extends Mapper&Object, Text,IntWritable,Text&{ int c=0; public void map(Object key, Text value, Context context ) throws IOException, InterruptedException { StringTokenizer itr = new StringTokenizer(value.toString()); IntWritable a=new IntWritable(Integer.parseInt(itr.nextToken())); Text b=new Text(itr.nextToken()); if(c&10){ System.out.println("sss"); context.write(a, b); c++; } } } public static class IntSumReducer extends
Reducer&Text, IntWritable, Text, IntWritable& {
private IntWritable result = new IntWritable();
public void reduce(Text key, Iterable&IntWritable& values,
Context context) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
result.set(sum);
context.write(key, result);
private static class IntWritableDecreasingComparator parator {
public int compare(WritableComparable a, WritableComparable b) {
System.out.println("ss"); return -pare(a, b);
public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
System.out.println("ss1"); return -pare(b1, s1, l1, b2, s2, l2);
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
String[] otherArgs = new GenericOptionsParser(conf, args)
.getRemainingArgs();
if (otherArgs.length != 2) {
System.err.println("Usage: wordcount &in& &out&");
System.exit(2);
Path tempDir = new Path("wordcount-temp-" + Integer.toString(
new Random().nextInt(Integer.MAX_VALUE))); //临时目录 Path tempDir2 = new Path("wordcount-temp2-" + Integer.toString(
new Random().nextInt(Integer.MAX_VALUE))); // Job job = new Job(conf, "word count");
job.setJarByClass(WordCount2.class);
job.setMapperClass(TokenizerMapper.class);
job.setCombinerClass(IntSumReducer.class);
job.setReducerClass(IntSumReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
FileOutputFormat.setOutputPath(job, tempDir);//先将词频统计任务的输出结果写到临时下一个排序任务以临时目录为输入目录。 job.setOutputFormatClass(SequenceFileOutputFormat.class);
if(job.waitForCompletion(true))
Job sortJob = new Job(conf, "sort");
sortJob.setJarByClass(WordCount2.class);
FileInputFormat.addInputPath(sortJob, tempDir);
sortJob.setInputFormatClass(SequenceFileInputFormat.class);
/*InverseMapper由hadoop库提供,作用是实现map()之后的数据对的key和value交换*/
sortJob.setMapperClass(InverseMapper.class);
/*将 Reducer 的个数限定为1, 最终输出的结果文件就是一个。*/ sortJob.setNumReduceTasks(1);
FileOutputFormat.setOutputPath(sortJob, tempDir2);
sortJob.setOutputKeyClass(IntWritable.class);
sortJob.setOutputValueClass(Text.class);
/*Hadoop 默认对 IntWritable 按升序排序,而我们需要的是按降序排列。
* 因此我们实现了一个 IntWritableDecreasingComparator 类,
* 并指定使用这个自定义的 Comparator 类对输出结果中的 key (词频)进行排序*/ sortJob.setSortComparatorClass(IntWritableDecreasingComparator.class);
if(sortJob.waitForCompletion(true)) { Job topJob = new Job(conf, "sort");
topJob.setJarByClass(WordCount2.class);
FileInputFormat.addInputPath(topJob, tempDir2);
//topJob.setInputFormatClass(SequenceFileInputFormat.class);
topJob.setMapperClass(TokenizerMapper2.class);
FileOutputFormat.setOutputPath(topJob, new Path(otherArgs[1]));
topJob.setOutputKeyClass(IntWritable.class);
topJob.setOutputValueClass(Text.class);
System.exit(topJob.waitForCompletion(true) ? 0 : 1);
} // System.exit(sortJob.waitForCompletion(true) ? 0 : 1);
FileSystem.get(conf).deleteOnExit(tempDir);

我要回帖

更多关于 文本编程 的文章

 

随机推荐