如何解决计算文件中每个单词出现的次数
| 嗨,我正在编写一个程序,该程序计算每个单词在文件中出现的次数。然后,它会打印一个计数在800到1000之间的单词列表,按计数顺序排序。我坚持要保持计数器,以查看第一个单词是否与下一个单词匹配,直到出现新单词为止。我主要尝试打开文件,逐个单词读取每个单词,然后在while循环中调用sort来对向量进行排序。然后,在for循环中遍历所有单词,如果第一个单词等于第二个++。我不认为这是您保持反击的方式。 这是代码:#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
vector<string> lines;
vector<int> second;
set<string> words;
multiset<string> multiwords;
void readLines(const char *filename)
{
string line;
ifstream infile;
infile.open(filename);
if (!infile)
{
cerr << filename << \" cannot open\" << endl;
return;
}
getline(infile,line);
while (!infile.eof())
{
lines.push_back(line);
getline(infile,line);
}
infile.close();
}
int binary_search(vector<string> &v,int size,int value)
{
int from = 0;
int to = size - 1;
while (from <= to)
{
int mid = (from + to) / 2;
int mid_count = multiwords.count(v[mid]);
if (value == mid_count)
return mid;
if (value < mid_count) to = mid - 1;
else from = mid + 1;
}
return from;
}
int main()
{
vector<string> words;
string x;
ifstream inFile;
int count = 0;
inFile.open(\"bible.txt\");
if (!inFile)
{
cout << \"Unable to open file\";
exit(1);
}
while (inFile >> x){
sort(words.begin(),words.end());
}
for(int i = 0;i < second.size();i++)
{
if(x == x+1)
{
count++;
}
else
return;
}
inFile.close();
}
解决方法
一种解决方案可能是:定义
letter_only
语言环境,以便忽略来自流的标点符号,并仅从输入流中读取有效的“英语”字母。这样,流将把\“ ways \”,\“ ways。\”和\“ ways!\”视为相同的单词\“ ways \”,因为流将忽略像\“这样的标点符号。 “和\”!\“。
struct letter_only: std::ctype<char>
{
letter_only(): std::ctype<char>(get_table()) {}
static std::ctype_base::mask const* get_table()
{
static std::vector<std::ctype_base::mask>
rc(std::ctype<char>::table_size,std::ctype_base::space);
std::fill(&rc[\'A\'],&rc[\'z\'+1],std::ctype_base::alpha);
return &rc[0];
}
};
然后将其用作:
int main()
{
std::map<std::string,int> wordCount;
ifstream input;
//enable reading only english letters only!
input.imbue(std::locale(std::locale(),new letter_only()));
input.open(\"filename.txt\");
std::string word;
std::string uppercase_word;
while(input >> word)
{
std::transform(word.begin(),word.end(),std::back_inserter(uppercase_word),(int(&)(int))std::toupper); //the cast is needed!
++wordCount[uppercase_word];
}
for (std::map<std::string,int>::iterator it = wordCount.begin();
it != wordCount.end();
++it)
{
std::cout << \"word = \"<< it->first
<<\" : count = \"<< it->second << std::endl;
}
}
,他。我知道直截了当地显示解决方案并没有真正帮助您。然而。
我浏览了一下您的代码,发现许多未使用和混乱的位。这是我要做的:
#include <algorithm>
#include <fstream>
#include <functional>
#include <iostream>
#include <iterator>
#include <map>
#include <string>
#include <vector>
using namespace std;
// types
typedef std::pair<string,size_t> frequency_t;
typedef std::vector<frequency_t> words_t;
// predicates
static bool byDescendingFrequency(const frequency_t& a,const frequency_t& b)
{ return a.second > b.second; }
const struct isGTE // greater than or equal
{
size_t inclusive_threshold;
bool operator()(const frequency_t& record) const
{ return record.second >= inclusive_threshold; }
} over1000 = { 1001 },over800 = { 800 };
int main()
{
words_t words;
{
map<string,size_t> tally;
ifstream inFile(\"bible.txt\");
string s;
while (inFile >> s)
tally[s]++;
remove_copy_if(tally.begin(),tally.end(),back_inserter(words),over1000);
}
words_t::iterator begin = words.begin(),end = partition(begin,words.end(),over800);
std::sort(begin,end,&byDescendingFrequency);
for (words_t::const_iterator it=begin; it!=end; it++)
cout << it->second << \"\\t\" << it->first << endl;
}
授权版本:
993 because
981 men
967 day
954 over
953 God,910 she
895 among
894 these
886 did
873 put
868 thine
864 hand
853 great
847 sons
846 brought
845 down
819 you,811 so
伏尔加塔:
995 tuum
993 filius
993 nec
966 suum
949 meum
930 sum
919 suis
907 contra
902 dicens
879 tui
872 quid
865 Domine
863 Hierusalem
859 suam
839 suo
835 ipse
825 omnis
811 erant
802 se
两个文件的性能大约为1.12s,但是在将map<>
替换为ѭ8after之后,只有0.355s。
,可以通过出现一次map< string,int >
,逐个读取单词,并在m[ word ]
中增加计数器来完成更有效的方法。在考虑完所有单词之后,遍历地图,对于给定范围内的单词,将它们添加到multimap<int,string>
中。最后转储多图的内容,该内容将按出现次数和字母顺序排序...
,只是为了好玩,我使用Boost MultiIndex以c ++ 0x风格做了一个解决方案。
没有auto
关键字(类型推断),此样式将非常笨拙。
通过始终按单词和按频率维护索引,无需删除,分区或对单词列表进行排序:它会一直存在。
要编译并运行:
g++ --std=c++0x -O3 test.cpp -o test
curl ftp://ftp.funet.fi/pub/doc/bible/texts/english/av.tar.gz |
tar xzO | sed \'s/^[ 0-9:]\\+//\' > bible.txt
time ./test
。
#include <boost/foreach.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/member.hpp>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
struct entry
{
string word;
size_t freq;
void increment() { freq++; }
};
struct byword {}; // TAG
struct byfreq {}; // TAG
int main()
{
using ::boost::lambda::_1;
using namespace ::boost::multi_index;
multi_index_container<entry,indexed_by< // sequenced<>,ordered_unique <tag<byword>,member<entry,string,&entry::word> >,// alphabetically
ordered_non_unique<tag<byfreq>,size_t,&entry::freq> > // by frequency
> > tally;
ifstream inFile(\"bible.txt\");
string s;
while (inFile>>s)
{
auto& lookup = tally.get<byword>();
auto it = lookup.find(s);
if (lookup.end() != it)
lookup.modify(it,boost::bind(&entry::increment,_1));
else
lookup.insert({s,1});
}
BOOST_FOREACH(auto e,tally.get<byfreq>().range(800 <= _1,_1 <= 1000))
cout << e.freq << \"\\t\" << e.word << endl;
}
注意如何
定义自定义entry
类型而不是使用std::pair
变得更加方便
(出于明显的原因),这比我之前的代码要慢:这在插入阶段按频率维护索引。这是不必要的,但是它可以更有效地提取[800,1000]范围:
tally.get<byfreq>().range(800 <= _1,_1 <= 1000)
已经订购了多组频率。因此,的实际速度/内存交易可能会偏向于此版本,特别是在文档较大且包含很少重复单词的情况下(尤其是,这是众所周知的属性,不适合圣经的语料库文本使用,以免受到干扰)有人将其翻译为新泻。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。