· 6 years ago · Sep 02, 2019, 11:36 PM
1#include "mainwindow.h"
2#include "ui_mainwindow.h"
3#include <bits/stdc++.h>
4#include <QDebug>
5
6using namespace std;
7
8const int ALPHABET_SIZE = 26;
9
10struct TrieNode
11{
12 struct TrieNode *child[ALPHABET_SIZE];
13 bool EndWord;
14 string mea;
15};
16
17struct TrieNode *getNode()
18{
19 struct TrieNode *nod = new TrieNode;
20 for (int i = 0; i < ALPHABET_SIZE; i++)
21 {
22 nod->child[i] = nullptr;
23 }
24 nod->EndWord = false;
25 nod->mea = "";
26 return nod;
27};
28
29void insert(struct TrieNode *root, string key, string meaning)
30{
31 transform(key.begin(), key.end(), key.begin(), ::tolower);
32 if (root == nullptr)
33 root = getNode();
34
35 struct TrieNode *api = root;
36 //make sure that all characters are in lowercase
37 for (int i = 0; i < key.length(); i++)
38 {
39 int index = key[i] - 'a';
40 if (!api->child[index])
41 api->child[index] = getNode();
42 api =api->child[index];
43 }
44 api->EndWord = true;
45 api->mea = meaning;
46};
47
48QString getMea(struct TrieNode *root, string key)
49{
50 transform(key.begin(), key.end(), key.begin(), ::tolower);
51 if (!root)
52 return "Invalid Word";
53
54 struct TrieNode *api = root;
55 for (int i = 0; i < key.length(); i++)
56 {
57 int index = key[i] - 'a';
58 api = api->child[index];
59 if (!api)
60 {
61 return "Invalid Word";
62 }
63 }
64 if (api->EndWord){
65 QString ans=QString::fromStdString(api->mea);
66 return ans;
67 }
68 return "Invalid Word";
69};
70
71void makedict(struct TrieNode *root, int numl)
72{
73 char *path=QCoreApplication::applicationDirPath().append("/dictionary/dictionary.csv").toLocal8Bit().data();
74 ifstream inFile;
75 inFile.open(path, ios::in | ios::binary);
76 if (!inFile)
77 {
78 cout << "Couldn't open the file" << endl;
79 return;
80 }
81
82 string s[numl];
83 string h[numl];
84 string t[numl];
85 string line;
86
87 int i = 0, p = 0, q = 0, z = 0;
88 while (getline(inFile, line))
89 {
90 int l = line.length();
91 // cout<<l<<endl;
92 for (i = 0; i < l; i++)
93 {
94 if (line[i] != ',')
95 {
96 s[q] = s[q] + line[i];
97 }
98 if (line[i] == ',')
99 {
100 for (p = 0; p < l - i - 1; p++)
101 {
102 h[q] = h[q] + line[i + p + 1];
103 } //cout<<""<<endl;
104 break;
105 }
106 }
107 q++;
108 }
109 for (z = 0; z < numl; z++)
110 {
111 insert(root, s[z], h[z]);
112 }
113}
114
115
116struct TrieNode* root;
117MainWindow::MainWindow(QWidget *parent) :
118 QMainWindow(parent),
119 ui(new Ui::MainWindow)
120{
121 root=getNode();
122 makedict(root,15);
123
124 ui->setupUi(this);
125}
126
127MainWindow::~MainWindow()
128{
129 delete ui;
130}
131//struct TrieNode* root=setDict();
132
133
134
135void MainWindow::on_pushButton_clicked()
136{
137 QString text = ui->textEdit->toPlainText();
138 string txt=text.toUtf8().constData();
139 QString out = getMea(root,txt);
140 ui->textEdit_2->setText(out);
141}