Question

In: Computer Science

The following code searches a text file for definitions and prints them out. I want to...

The following code searches a text file for definitions and prints them out.

I want to create a function that can be called for the given vector and map. The function will either print the results in reverse order, print results without duplicate definitions, or do both. What is the best approach to make the code less repetitive.

if (find(keyWords.begin(), keyWords.end(), v[0]) != keyWords.end()) {
                       for (auto map_iter = mymap.cbegin(); map_iter != mymap.cend(); ++map_iter) {
                           if (v[0] == map_iter->first) {
                               for (auto vec_iter = map_iter->second.cbegin(); vec_iter != map_iter->second.cend(); ++vec_iter)
                                   cout << " " << wordSearch << " " << *vec_iter << endl;
                           }
                       }

Solutions

Expert Solution

Working code implemented in C++ and appropriate comments provided for better understanding.

Source Code:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <map>
#include <list>
#include <algorithm>

using namespace std;
void replaceAll(string &s, const string &search, const string &replace);
string replaceWordSearch(string word);

int main() {
   string line;
   ifstream file("Data.CS.SFSU.txt");
   map<string, vector<string>> mymap;

   if (file.is_open()) {
       cout << "! Opening data file... ./Data.CS.SFSU.txt" << endl;
       cout << "! Loading data..." << endl;

       while (getline(file, line)) {
           istringstream ss(line);
           string token;
           vector<string> myvector;
           vector<string> newvector;
           vector<string> finalvector;

           //breaks each line into tokens at each occurance of '|'
           while (getline(ss, token, '|')) {
               myvector.push_back(token);
           }

           //gets rid of first entry in vector(name) and makes newvector
           for (int i = 1; i < myvector.size(); i++) {
               newvector.push_back(myvector[i]);
           }

           //the word key value
           string tempkey = myvector[0];

           //edit the newvector here to match format of desired output and put into new finalvector
           for (int i = 0; i < newvector.size(); i++) {
               string temp = newvector[i];
               replaceAll(temp, "=>", " ");
               replaceAll(temp, "noun ", "[noun] : ");
               replaceAll(temp, "adjective ", "[adjective] : ");
               replaceAll(temp, "verb ", "[verb] : ");
               finalvector.push_back(temp);
           }

           //place all entries into map of with key=word and value=vector<string> of definitions
           mymap.insert(make_pair(tempkey, finalvector));
       }

       //close file and output closed file alert
       file.close();
       cout << "! Loading completed..." << endl;
       cout << "! Closing data file... ./Data.CS.SFSU.txt" << endl;
   }

   //welcome message
   cout << endl;
   cout << "----- DICTIONARY 340 C++----- " << endl;
   cout << endl;

   //creates a vector of key values to search if the userinput is valid (later in program)
   vector<string> keyWords;

   for (map<string, vector<string>>::iterator it = mymap.begin(); it != mymap.end(); it++) {
       keyWords.push_back(it->first);
   }


   //gets user input
   while (true) {
       cout << "Search: ";
       string input;
       getline(cin, input);

       //if nothing is entered, output error
       if (input == "") {
           cout << " |" << endl;
           cout << " <Please enter a search key (and a part of speech).>" << endl;
           cout << " |" << endl;
       }
       else {
           //makes userinput lowercase to match the vector of keyvalues for validation
           for (int i = 0; i < input.length(); i++) {
               input[i] = tolower(input[i]);
           }

           istringstream s2(input);
           vector<string> v;
           string tmp;

           //puts user input into vector
           while (s2 >> tmp) {
               v.push_back(tmp);
           }


           string wordSearch = v[0];
           wordSearch = replaceWordSearch(wordSearch);

           //proccesses user input **********************************************************************


           //if !Q entered, exit program
           if ((v[0] == "!Q") || (v[0] == "!q")) {
               cout << endl;
               cout << "----- THANK YOU----- " << endl;
               break;
           }
           else {

               cout << " |" << endl;

               //if nothing is entered, output error message
               if (v.size() == 0) {
                   cout << " <Please enter a search key (and a part of speech).>" << endl;

               }

               //if one word is entered, output definitions or error message
               if (v.size() == 1) {
                   if (find(keyWords.begin(), keyWords.end(), v[0]) != keyWords.end()) {
                       //iterate through map and find keyword, print all values in vector
                       for (auto map_iter = mymap.cbegin(); map_iter != mymap.cend(); ++map_iter) {
                           if (v[0] == map_iter->first) {
                               for (auto vec_iter = map_iter->second.cbegin(); vec_iter != map_iter->second.cend(); ++vec_iter)
                                   std::cout << " " << wordSearch << " " << *vec_iter << endl;


                           }
                       }
                   }
                   else {
                       cout << " <Not found.>" << endl;

                   }
               }

               //if two or more words are entered, output definition or error message
               if (v.size() == 2) {
                   if ((v[1] != "noun") && (v[1] != "adjective") && (v[1] != "verb")) {
                       cout << " <2nd argument must be a part of speech.>" << endl;

                   }
                   else {
                       if (find(keyWords.begin(), keyWords.end(), v[0]) != keyWords.end()) {
                           //cout << "return vector >> if pos if found return definition" << endl;

                           for (auto map_iter = mymap.cbegin(); map_iter != mymap.cend(); ++map_iter) {
                               if (v[0] == map_iter->first) {
                                   if ((v[1] == "noun") || (v[1] == "adjective") || (v[1] == "verb")) {
                                       int count = 0;
                                       for (auto vec_iter = map_iter->second.cbegin(); vec_iter != map_iter->second.cend(); ++vec_iter) {
                                           string str1 = *vec_iter;
                                           string str2 = v[1];
                                           if (str1.find(str2) != string::npos) {
                                               std::cout << " " << wordSearch << " " << *vec_iter << endl;
                                               count++;
                                           }
                                       }
                                       if (count == 0) {
                                           cout << " <Not found.>" << endl;

                                       }
                                   }
                                   else {
                                       cout << " <Not found.>" << endl;

                                   }
                               }
                           }
                       }
                       else {
                           cout << " <Not found.>" << endl;

                       }
                   }
               }
               if (v.size() > 2) {
                   cout << " <Please enter a search key (and a part of speech).>" << endl;

               }
               cout << " |" << endl;
           }
       }
   }
   return 0;
}

void replaceAll(string &s, const string &search, const string &replace) {
   for (size_t pos = 0; ; pos += replace.length()) {
       // Locate the substring to replace
       pos = s.find(search, pos);
       if (pos == string::npos) break;
       // Replace by erasing and inserting
       s.erase(pos, search.length());
       s.insert(pos, replace);
   }
}


string replaceWordSearch(string word) {
   if (word == "book")
       return "Book";
   if (word == "bookable")
       return "Bookable";
   if (word == "bookbinder")
       return "Bookbinder";
   if (word == "bookcase")
       return "Bookcase";
   if (word == "csc210")
       return "CSC210";
   if (word == "csc220")
       return "CSC220";
   if (word == "csc340")
       return "CSC340";
   else
       return word;
}

Sample Output Screenshots:


Related Solutions

Write a program that computes and prints the average of numbers in a text file. I...
Write a program that computes and prints the average of numbers in a text file. I created a text file integers.txt that has the numbers 5,4,3,2,1. I need to define the average function Define the main function which will include the following things 1. prompt user for input of text file name 2. open and read input file, can be done before or inside high order functions 3. use two high order functions 4.calculate and display averages and original ist...
Java Write a method that reads a text file and prints out the number of words...
Java Write a method that reads a text file and prints out the number of words at the end of each line
For c language. I want to read a text file called input.txt for example, the file...
For c language. I want to read a text file called input.txt for example, the file has the form. 4 hello goodbye hihi goodnight where the first number indicates the n number of words while other words are separated by newlines. I want to store these words into a 2D array so I can further work on these. and there are fewer words in the word file than specified by the number in the first line of the file, then...
Whats the code to open a text file and every line in that text file that...
Whats the code to open a text file and every line in that text file that starts with # then it should delete that line In python using .strip
Create a program that generates a file of random numbers, and then prints them in neat...
Create a program that generates a file of random numbers, and then prints them in neat fashion to another file, and also saves to that file the average and standard deviation of those numbers. I) First, you would need to generate a file of random numbers that consists of N random numbers (100 < N < 1000). Each random digit should be a real number (type double) between 0 and 50. This file and its digits would now serve as...
I have a Python code that reads the text file, creates word list then calculates word...
I have a Python code that reads the text file, creates word list then calculates word frequency of each word. Please see below: #Open file f = open('example.txt', 'r') #list created with all words data=f.read().lower() list1=data.split() #empty dictionary d={} # Adding all elements of the list to a dictionary and assigning it's value as zero for i in set(list1):     d[i]=0 # checking and counting the values for i in list1:     for j in d.keys():        if i==j:           d[i]=d[i]+1 #Return all non-overlapping...
Use Python to Complete the following on a single text file and submit your code and...
Use Python to Complete the following on a single text file and submit your code and your output as separate documents. For each problem create the necessary list objects and write code to perform the following examples: Sum all the items in a list. Multiply all the items in a list. Get the largest number from a list. Get the smallest number from a list. Remove duplicates from a list. Check a list is empty or not. Clone or copy...
Write a code to find the following in a text file (Letter). language: Python (a) Find...
Write a code to find the following in a text file (Letter). language: Python (a) Find the 20 most common words (b) How many unique words are used? (c) How many words are used at least 5 times? (d) Write the 200 most common words, and their counts, to a file. text file: Look in thy glass and tell the face thou viewest, Now is the time that face should form another, Whose fresh repair if now thou not renewest,...
These code are correct, and I want some explanation or comment for them(purpose for each function)...
These code are correct, and I want some explanation or comment for them(purpose for each function) def annoying_factorial(n): if n == 0 or n == 1: return 1 if n == 2: return 2 if n == 3: return 6 if n == 4: return 4 * annoying_factorial(3) if n == 5: return 5 * annoying_factorial(4) if n == 6: return 6 * annoying_factorial(5) else: return n * annoying_factorial(n-1) def annoying_fibonacci(n): if n==0: return 0 if n==1: return 1 if...
Write a c program that reads a .img file by rows and columns and prints out...
Write a c program that reads a .img file by rows and columns and prints out the arrays. The .img file contains h(the height) and w(the width) of the text size. An example .img file would be: 2 4 DFJSK HJ5JF HFDY5
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT