1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
#include <iostream> #include <string> #include <map> #include <sstream> #include <algorithm> class SimpleNLP { private: std::map<std::string, int> wordFrequency; // To store word frequency public: // Function to process a text input and count word frequencies void processText(const std::string& text) { std::string word; std::istringstream stream(text); while (stream >> word) { // Remove punctuation from the word word.erase(std::remove_if(word.begin(), word.end(), ::ispunct), word.end()); // Convert to lowercase std::transform(word.begin(), word.end(), word.begin(), ::tolower); // Update word frequency ++wordFrequency[word]; } } // Function to display the word frequencies void displayWordFrequencies() const { std::cout << "Word Frequencies:\n"; for (const auto& pair : wordFrequency) { std::cout << pair.first << ": " << pair.second << "\n"; } } }; int main() { std::string text; // Input text from the user std::cout << "Enter the text for NLP processing (end input with an empty line):\n"; std::getline(std::cin, text); // Create a SimpleNLP object SimpleNLP nlp; // Process the input text nlp.processText(text); // Display the word frequencies nlp.displayWordFrequencies(); return 0; } |
Explanation
- Class Definition (
SimpleNLP
):- Private Members:
wordFrequency
: Astd::map
to store the frequency of each word in the text.
- Private Members:
processText
Method:- Takes a string of text as input and processes it to count the frequency of each word.
- Uses
std::istringstream
to tokenize the input text. - Removes punctuation from each word and converts it to lowercase to ensure uniformity.
- Updates the word frequency count in the
wordFrequency
map.
displayWordFrequencies
Method:- Outputs the frequency of each word stored in the
wordFrequency
map.
- Outputs the frequency of each word stored in the
main
Function:- Prompts the user to input text for processing.
- Creates an instance of
SimpleNLP
. - Calls
processText
to analyze the text and count word frequencies. - Calls
displayWordFrequencies
to display the results.