-
Notifications
You must be signed in to change notification settings - Fork 0
/
pronounce_dict.cpp
86 lines (80 loc) · 2.74 KB
/
pronounce_dict.cpp
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
/**
* @file pronounce_dict.cpp
* Implementation of the PronounceDict class.
*
* @author Matt Joras
* @date Winter 2013
*/
#include "pronounce_dict.h"
#include <iterator>
#include <sstream>
#include <fstream>
#include <iostream>
#include <cstring>
#include <algorithm>
using std::string;
using std::map;
using std::vector;
using std::ifstream;
using std::istream;
using std::istream_iterator;
using std::stringstream;
/**
* Constructs a PronounceDict from a CMU pronunciation dictionary
* file. See http://www.speech.cs.cmu.edu/cgi-bin/cmudict .
* @param pronun_dict_filename Filename of the CMU pronunciation
* dictionary.
*/
PronounceDict::PronounceDict(const string& pronun_dict_filename)
{
ifstream pronun_dict_file(pronun_dict_filename);
string line;
if (pronun_dict_file.is_open()) {
while (getline(pronun_dict_file, line)) {
/* Used to break the line by whitespace. The CMU Dict does this for
* separating words from their pronunciations. */
stringstream line_ss(line);
istream_iterator<string> line_begin(line_ss);
istream_iterator<string> line_end;
if (line[0] != '#' && *line_begin != ";;;") {
/* Associate the word with the rest of the line
* (its pronunciation). */
auto temp_itr = line_begin;
dict[*temp_itr] = vector<string>(++line_begin, line_end);
}
}
}
/* If it's not open then... well... just don't do anything for the sake
* of simplicity. */
}
/**
* Constructs a PronounceDict from a CMU std::map mapping the word
* to a vector of strings which represent the pronunciation.
* @param pronun_dict Maps a string word to a vector of strings
* representing its pronunciation.
*/
PronounceDict::PronounceDict(const map<string, vector<string>>& pronun_dict)
: dict(pronun_dict)
{
/* Nothing to see here. */
}
/**
* Uses the dictionary to determine if the two words are homophones.
* @param word1 First word to be tested.
* @param word2 Second word to be tested.
* @return true if the two words are homophones, false otherwise (or
* one or both words weren't in the dictionary).
* Note: The word keys in the dictionary are stored in uppercase.
* Note: word1 and word2 should **not** be modified after the
* function ends.
*/
bool PronounceDict::homophones(const string& word1, const string& word2) const
{
/* Your code goes here! */
std::string w1, w2;
w1.assign(word1);
w2.assign(word2);
std::transform(w1.begin(), w1.end(), w1.begin(), ::toupper);
std::transform(w2.begin(), w2.end(), w2.begin(), ::toupper);
return (dict.find(w1)!=dict.end() && dict.find(w2)!=dict.end()) && (dict.find(w1)->second == dict.find(w2)->second);
}