| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
|
|
Ajax Application Generator Generate database and reporting .NET Web apps in minutes. Quickly create visually stunning, feature-rich apps that are easy to customize and ready to deploy. Download Now!
|
|
#1
|
|||
|
|||
|
C++ Frequency of words and phrases
Hi all,
I am developing a programme that reads a text file and counts the frequency of phrases. A phrase is a sequence of one or more words, my programme limits a phrase to 10 words, it also counts 'the' and 'The' equal, hence suppresses case sensitivity. I have created a programme that reads a text file however i cannot seem to make it work correctly, i also intend to change to the following output Phrases of 2 word(s): of the : 23 final state : 15 isotope production : 14 energy loss : 12 for the : 10 in the : 9 state production : 8 by the : 7 in a : 7 to the : 7 and so on for three, four.... Code:
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <vector>
using namespace std;
struct Phrase {
void display() const
{
for (int i = 0; i < words.size(); ++i)
cout << words[i] << " ";
}
vector<string> words;
};
bool operator<(const Phrase& lhs, const Phrase& rhs)
{
return lhs.words < rhs.words;
}
int main()
{
ifstream input("input.txt");
if (!input)
{
cout << "Can't open input file: input.txt\n";
return 1;
}
const int LIMIT = 10;
Phrase cur;
map<Phrase, int> stat;
string word;
while (input >> word)
{
for (int i = 0; i < word.size(); ++i)
word[i] = tolower(word[i]);
if (cur.words.size() == LIMIT)
{
++stat[cur];
cur.words.clear();
}
cur.words.push_back(word);
}
if (!cur.words.empty())
++stat[cur];
cout << "Phrase frequencies:\n";
map<Phrase, int>::const_iterator iter = stat.begin();
for (; iter != stat.end(); ++iter)
{
iter->first.display();
cout << ": "
<< iter->second << " times\n";
}
return 0;
}
I would appreciate any help which would point out where I am going wrong and how I can adapt my code, to the above output. Thank you |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > C++ Frequency of words and phrases |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|
|