-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtextprocessing.go
698 lines (626 loc) · 19.7 KB
/
textprocessing.go
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
// Calum Bell - 24016526 - Computer Science - 21/11/17
// CAPS Final Subtask - Text Processing in GoLang
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"sort"
"strings"
"time"
)
/* Word Struct -
* This struct is used to map the array to a frequencies table
*/
type word struct {
word string
frequency int // Number of times found
}
/* Keyword Struct -
* The keyword struct is populated with user input and then converted to json
* to be sent to the server
*/
type Keyword struct {
Keyword string
}
// Stopwords to ignore during output sourced from - https://github.com/bbalet/stopwords
var stopwords = map[string]string{
"1": "",
"2": "",
"3": "",
"4": "",
"5": "",
"6": "",
"7": "",
"8": "",
"9": "",
"ebay": "",
"a": "",
"about": "",
"above": "",
"across": "",
"after": "",
"afterwards": "",
"again": "",
"against": "",
"all": "",
"almost": "",
"alone": "",
"along": "",
"already": "",
"also": "",
"although": "",
"always": "",
"am": "",
"among": "",
"amongst": "",
"amoungst": "",
"amount": "",
"an": "",
"and": "",
"another": "",
"any": "",
"anyhow": "",
"anyone": "",
"anything": "",
"anyway": "",
"anywhere": "",
"are": "",
"around": "",
"as": "",
"at": "",
"back": "",
"be": "",
"became": "",
"because": "",
"become": "",
"becomes": "",
"becoming": "",
"been": "",
"before": "",
"beforehand": "",
"behind": "",
"being": "",
"below": "",
"beside": "",
"besides": "",
"between": "",
"beyond": "",
"bill": "",
"both": "",
"bottom": "",
"but": "",
"by": "",
"call": "",
"can": "",
"cannot": "",
"cant": "",
"co": "",
"con": "",
"com": "",
"could": "",
"couldnt": "",
"cry": "",
"de": "",
"describe": "",
"detail": "",
"do": "",
"done": "",
"down": "",
"due": "",
"during": "",
"each": "",
"eg": "",
"eight": "",
"either": "",
"eleven": "",
"else": "",
"elsewhere": "",
"empty": "",
"enough": "",
"etc": "",
"even": "",
"ever": "",
"every": "",
"everyone": "",
"everything": "",
"everywhere": "",
"except": "",
"few": "",
"fifteen": "",
"fify": "",
"fill": "",
"find": "",
"fire": "",
"first": "",
"five": "",
"for": "",
"former": "",
"formerly": "",
"forty": "",
"found": "",
"four": "",
"from": "",
"front": "",
"full": "",
"further": "",
"get": "",
"give": "",
"go": "",
"had": "",
"has": "",
"hasnt": "",
"have": "",
"he": "",
"hence": "",
"her": "",
"here": "",
"hereafter": "",
"hereby": "",
"herein": "",
"hereupon": "",
"hers": "",
"herself": "",
"him": "",
"himself": "",
"his": "",
"how": "",
"however": "",
"hundred": "", // Custom Insertions
"http": "",
"https": "",
"html": "",
"gif": "",
"jpg": "",
"utf8": "",
"s": "",
"ie": "", // -----------------
"if": "",
"in": "",
"inc": "",
"indeed": "",
"interest": "",
"into": "",
"is": "",
"it": "",
"its": "",
"itself": "",
"keep": "",
"last": "",
"latter": "",
"latterly": "",
"least": "",
"less": "",
"ltd": "",
"made": "",
"many": "",
"may": "",
"me": "",
"meanwhile": "",
"might": "",
"mill": "",
"mine": "",
"more": "",
"moreover": "",
"most": "",
"mostly": "",
"move": "",
"much": "",
"must": "",
"my": "",
"myself": "",
"name": "",
"namely": "",
"neither": "",
"never": "",
"nevertheless": "",
"next": "",
"nine": "",
"no": "",
"nobody": "",
"none": "",
"noone": "",
"nor": "",
"not": "",
"nothing": "",
"now": "",
"nowhere": "",
"of": "",
"off": "",
"often": "",
"on": "",
"once": "",
"one": "",
"only": "",
"onto": "",
"or": "",
"other": "",
"others": "",
"otherwise": "",
"our": "",
"ours": "",
"ourselves": "",
"out": "",
"over": "",
"own": "",
"part": "",
"per": "",
"perhaps": "",
"please": "",
"put": "",
"rather": "",
"re": "",
"same": "",
"see": "",
"seem": "",
"seemed": "",
"seeming": "",
"seems": "",
"serious": "",
"several": "",
"she": "",
"should": "",
"show": "",
"side": "",
"since": "",
"sincere": "",
"six": "",
"sixty": "",
"so": "",
"some": "",
"somehow": "",
"someone": "",
"something": "",
"sometime": "",
"sometimes": "",
"somewhere": "",
"still": "",
"such": "",
"system": "",
"take": "",
"ten": "",
"than": "",
"that": "",
"the": "",
"their": "",
"them": "",
"themselves": "",
"then": "",
"thence": "",
"there": "",
"thereafter": "",
"thereby": "",
"therefore": "",
"therein": "",
"thereupon": "",
"these": "",
"they": "",
"thickv": "",
"thin": "",
"third": "",
"this": "",
"those": "",
"though": "",
"three": "",
"through": "",
"throughout": "",
"thru": "",
"thus": "",
"to": "",
"together": "",
"too": "",
"top": "",
"toward": "",
"towards": "",
"twelve": "",
"twenty": "",
"two": "",
"un": "",
"under": "",
"until": "",
"up": "",
"upon": "",
"us": "",
"very": "",
"via": "",
"was": "",
"we": "",
"well": "",
"were": "",
"what": "",
"whatever": "",
"when": "",
"whence": "",
"whenever": "",
"where": "",
"whereafter": "",
"whereas": "",
"whereby": "",
"wherein": "",
"whereupon": "",
"wherever": "",
"whether": "",
"which": "",
"while": "",
"whither": "",
"who": "",
"whoever": "",
"whole": "",
"whom": "",
"whose": "",
"why": "",
"will": "",
"with": "",
"wiki": "",
"within": "",
"without": "",
"would": "",
"www": "",
"yet": "",
"you": "",
"your": "",
"yours": "",
"yourself": "",
"yourselves": ""}
/* Main function -
* Handles the HTTP request and creates the parseManager to break down the response
*/
func main() {
url := "http://127.0.0.1:8080/search/bing"
/* ----- Get User Input ----- */
inputtedWord := ""
fmt.Println("URL:>", url)
fmt.Println("Please enter a keyword to search for: ")
fmt.Scanln(&inputtedWord)
/* --------------------------- */
// Use JSON.marshall to convert the struct to JSON format
/* ----- Convert To JSON ----- */
// Convert our inputtedWord String to a JSON object
key := Keyword{inputtedWord}
// Convert that struct to JSON
buf, err := json.Marshal(key)
/* Handle any Errors */
if err != nil {
log.Fatal(err) // Throw fatal error & print to console
}
var jsonStr = []byte(buf) // Convert to format which the server accepts
/*-------------------*/
fmt.Printf("%s\n", buf)
/* --------------------------- */
/* ----- Request from Server ----- */
// Create the request with the JSON object we made
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json") // Set Header to JSON-type
client := &http.Client{} // Create a 'client' from the http library
resp, err := client.Do(req) // Use the .Do function to send the request
/* Handle any Errors */
if err != nil {
fmt.Printf("There was an error connecting to the server", err)
panic(err)
}
/*-------------------*/
defer resp.Body.Close()
fmt.Println("Response Status:", resp.Status)
fmt.Println("Response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
/* ---------------------------------- */
/* File I/O */
if resp.Status == "200 OK" {
fmt.Printf("\nPrinting output to sampleresponse.txt!")
responseFile, _ := os.OpenFile("sampleresponse.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666) // create file if not existing, and append to it. 666 = permission bits rw-/rw-/rw-
responseFile.WriteString(string(body))
defer responseFile.Close()
parseManager(string(body), inputtedWord)
} else {
fmt.Printf("\nServer request failed! Attempting to use local file instead.\n\n")
byteResponse, err := ioutil.ReadFile("sampleresponse.txt") // just pass the file name
if err != nil {
fmt.Print(err)
}
stringResponse := string(byteResponse)
parseManager(stringResponse, inputtedWord)
}
/* -------- */
// Create a parse manager to handle the response
// Keep the process alive -
for {
}
}
/* parseManager -
* Initialises the parsers and channels to run the analysis in parallel
* Provides the user with the ability to see the raw response
* Listens on each channel for the response of the parsers
* Combines the results of each parser in the finalArray
* Sorts the final array into a map in descending frequency order
*/
func parseManager(body string, keyword string) {
/* ----- Initialise variables ----- */
textString := strings.ToLower(body) // put all words in body to lowercase
re := regexp.MustCompile("\\w+") // * Define a regex expression to remove whitespace and punctuation
textArray := re.FindAllString(textString, -1) // Take all valid words from the string and put them in textArray
const noParsers = 1 // Number of threads, can be dynamic
workToDo := len(textArray) // Find out how many words we need to process
var allocatedWork = workToDo / noParsers
var leftoverWork = workToDo % noParsers
var finalMap map[string]int = map[string]int{} // parser results are combined into this map
var finalTable []word // Stores the sorted word structs
seeRawResponse := 'N' // Stores user input
/* ------------------------------- */
/* - Initialise array to store parser I/O channels - */
// Initialise channel from parser to parseManager containing the frequency map - [word : frequency]
var outputChannels [noParsers]chan map[string]int
// Initialise channel from parseManager to parser containing the array slice of work
var inputChannels [noParsers]chan []string
/* ------------------------------------------------- */
/* ----- Get User Input & Print Information ----- */
fmt.Printf("\nparseManager was born!")
fmt.Printf("\nparseManager recieved %v chars related to %v\n", workToDo, keyword)
fmt.Printf("\nDo you want to see the raw response? Y/N\n\n")
fmt.Scanln(&seeRawResponse) // Read from the console
if seeRawResponse == 78 {
fmt.Println(body)
}
fmt.Printf("\n-------------------------------")
fmt.Printf("\n|-------Initialising Data------|")
fmt.Printf("\n-------------------------------")
fmt.Printf("\nNumber of Parsers: %v", noParsers)
fmt.Printf("\nTotal Work to Complete: %v", workToDo)
fmt.Printf("\nAllocated Work: %v", allocatedWork)
fmt.Printf("\nRemainder Work: %v", leftoverWork)
fmt.Printf("\n-------------------------------\n\n")
/* ---------------------------------------------- */
/* ----- Generate Channels, Parsers and assign work --- */
/* Generate and send each parser their section of work */
/* Calculate Time */
i := 0
for i < noParsers {
// Make and store the channels for this Parser
inputChannels[i] = make(chan []string)
outputChannels[i] = make(chan map[string]int)
fmt.Printf("\nCreating Parser #%v", i)
go parser(i, inputChannels[i], outputChannels[i])
if i == (noParsers - 1) { // If we are the last parser, recieve any 'leftover work'
fmt.Printf("\nSending Slice [%v:%v] to #%v", (allocatedWork * i), (allocatedWork*i)+allocatedWork+leftoverWork, i)
work := textArray[(allocatedWork * i) : ((allocatedWork*i)+allocatedWork)+leftoverWork]
inputChannels[i] <- work
} else {
fmt.Printf("\nSending Slice [%v:%v] to #%v", (allocatedWork * i), (allocatedWork*i)+allocatedWork, i)
work := textArray[(allocatedWork * i):((allocatedWork * i) + allocatedWork)] //fmt.Printf("\nSending %v words to Parser %v", len(work), i)
inputChannels[i] <- work
}
i += 1
}
/* ------------------------------------------- */
/* ---------- Listen and combine completed work ---------- */
/* Listen on each channel and add results to a final array */
start := time.Now()
count := 0
for count < noParsers {
select {
case newMap := <-outputChannels[0]:
{ // Listen on the first channel
for k, v := range newMap {
finalMap[k] += v
}
count += 1
}
}
}
timeAfterProcess := time.Now()
elapsedPostProcess := timeAfterProcess.Sub(start)
fmt.Printf("\nTime Taken to process into frequency map: %v", elapsedPostProcess)
/* ----------------------------------------------------- */
/* ---------- Sort Results into Table ------------ */
fmt.Printf("\nResults Generated!\n")
for k, v := range finalMap {
finalTable = append(finalTable, word{k, v})
}
sort.Slice(finalTable, func(i, j int) bool {
return finalTable[i].frequency > finalTable[j].frequency
})
// Print Raw Table
// for _, word := range finalTable {
// fmt.Printf("%s, %d\n", word.word, word.frequency)
// }
/* ------------------------------------------------- */
timeAfterSort := time.Now()
elapsedPostSort := timeAfterSort.Sub(start)
totalTime := elapsedPostSort + elapsedPostProcess
var timePerWord float64
timePerWord = float64(workToDo) / float64(totalTime)
var wordsPerSecond float64
wordsPerSecond = float64(totalTime) / float64(workToDo)
/* ---------------- File Output ------------------ */
fmt.Printf("\nPrinting results to results.txt!")
responseFile, _ := os.OpenFile("results.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666) // create file if not existing, and append to it. 666 = permission bits rw-/rw-/rw-
responseFile.WriteString("\n|---------------------------------------------|")
responseFile.WriteString("\n|----------------- Completed! ----------------|")
responseFile.WriteString("\n|---------------------------------------------|")
responseFile.WriteString(fmt.Sprintf("\n| Search Term: %v |", keyword))
responseFile.WriteString(fmt.Sprintf("\n|---------------------------------------------|"))
responseFile.WriteString(fmt.Sprintf("\n| Number of Parsers: %v |", noParsers))
responseFile.WriteString(fmt.Sprintf("\n| Total Work to Complete: %v |", workToDo))
responseFile.WriteString(fmt.Sprintf("\n| Allocated Work: %v |", allocatedWork))
responseFile.WriteString(fmt.Sprintf("\n| Remainder Work: %v |", leftoverWork))
responseFile.WriteString("\n|----------------- Time Taken ----------------|")
responseFile.WriteString(fmt.Sprintf("\n| Time Taken to process into frequency map: |\n| %v |", elapsedPostProcess))
responseFile.WriteString(fmt.Sprintf("\n| Time Taken to sort into table: %v |", elapsedPostSort))
responseFile.WriteString(fmt.Sprintf("\n| Total Time Taken: %v |", totalTime))
responseFile.WriteString(fmt.Sprintf("\n| Time Taken per word: %vms/word |", timePerWord))
responseFile.WriteString("\n|---------------------------------------------|")
responseFile.WriteString("\n|------- Top Ten Results (- Stop Words)-------|")
responseFile.WriteString("\n|---------------------------------------------|")
numberOfResults := 0
for i := 0; numberOfResults < 10; i++ {
_, exists := stopwords[finalTable[i].word]
if exists == true {
} else { // Start at 1
responseFile.WriteString(fmt.Sprintf("\n| %v : %v", finalTable[i].word, finalTable[i].frequency))
numberOfResults++
}
}
defer responseFile.Close()
/* ------------------------------------------------- */
/* ---------------- Screen Output ------------------ */
fmt.Printf("\n|---------------------------------------------|")
fmt.Printf("\n|----------------- Completed! ----------------|")
fmt.Printf("\n|---------------------------------------------|")
fmt.Printf("\n| Search Term: %v |", keyword)
fmt.Printf("\n|---------------------------------------------|")
fmt.Printf("\n| Number of Parsers: %v ", noParsers)
fmt.Printf("\n| Total Work to Complete: %v ", workToDo)
fmt.Printf("\n| Allocated Work: %v ", allocatedWork)
fmt.Printf("\n| Remainder Work: %v ", leftoverWork)
fmt.Printf("\n|----------------- Time Taken ----------------|")
fmt.Printf("\n| Time Taken to process into frequency map: \n| %v |", elapsedPostProcess)
fmt.Printf("\n| Time Taken to sort into table: %v ", elapsedPostSort)
fmt.Printf("\n| Total Time Taken: %v ", totalTime)
// fmt.Printf("\n| Time Taken per word: %v ms/word ", timePerWord)
fmt.Printf("\n| Words per second: %v word/sec ", wordsPerSecond)
fmt.Printf("\n|---------------------------------------------|")
fmt.Printf("\n|------- Top Ten Results (- Stop Words)-------|")
fmt.Printf("\n|---------------------------------------------|")
numberOfResults = 0
for i := 0; numberOfResults < 10; i++ {
_, exists := stopwords[finalTable[i].word]
if exists == true {
} else { // Start at 1
fmt.Printf("\n| %v : %v", finalTable[i].word, finalTable[i].frequency)
numberOfResults++
}
}
fmt.Printf("\n|---------------------------------------------|\n\n")
/* ------------------------------------------------- */
}
/* parser -
* Takes an arraySlice from parseManager via the todo channel
* Converts the array to a frequencies map of word structs
* Sends the map back to parseManager via the done channel
*/
func parser(id int, todo <-chan []string, done chan map[string]int) {
fmt.Printf("\nParser #%v is now running!", id)
var wordsToParse = <-todo // Recieve work from parseManager
fmt.Printf("\nParser #%v has %v words to process: \n", id, len(wordsToParse))
// Frequency table - each word has an associated value - [word, frequency]
frequencies := make(map[string]int)
// range string slice gives index, word pairs
// For each word in our slice, set word to the word at index
// Range gives each word and the index its at, index isn't used so we use '_'
for _, word := range wordsToParse {
// Get the current value for this word from the map
_, freq := frequencies[word]
// If this value exists, add one
if freq == true {
frequencies[word] += 1
} else { // Start at 1
frequencies[word] = 1
}
}
// fmt.Print(frequencies)
done <- frequencies
}