-
Notifications
You must be signed in to change notification settings - Fork 8
/
ndic.bash
executable file
·139 lines (109 loc) · 2.35 KB
/
ndic.bash
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
#!/bin/bash
if [[ -z $BASH ]]; then
cat >&2 <<MSG
Ndic is a bash program, and musb be run with bash.
MSG
exit 1
fi
# variables
word=''
meanings=()
is_debug=false
is_speakable=false
main () {
if [[ -z $1 ]]; then
print_help
exit 1
fi
# reset option index
OPTIND=1
# parse arguments
while getopts 'hdsc' opt; do
case $opt in
h) # help
print_help
exit 0
;;
d) # turn on debug
is_debug=true
;;
s) # speak word
is_speakable=true
;;
c) # get the clipboard
word=$(pbpaste)
echo "$word"
;;
*)
print_help
exit 1
;;
esac
done
# set word if empty
[[ -z "$word" ]] && word=${@:$OPTIND}
debug "WORD: $word"
if [[ $word ]]; then
search # search only if the word is not empty
fi
}
debug () {
if $is_debug; then
echo "$@"
fi
}
search () {
local url result
url=`get_url`
result=`curl -s "$url"`
debug "URL: $url"
print_result "$result"
speak_word
}
get_url () {
# use mobile assistant dictionary
echo "https://endic.naver.com/searchAssistDict.nhn?query=${word// /%20}"
}
print_result () {
local str="$1"
local regex='<span class="fnt_k20"><strong>([^<]+)</strong></span>'
debug "HTML: $str"
while [[ $str =~ $regex ]]; do
# print meaning
echo "${BASH_REMATCH[1]}"
# store meaning to array
meanings+=("${BASH_REMATCH[1]}")
# delete matched string
str=${str/"${BASH_REMATCH}"/}
done
}
speak_word () {
# If the results exists and OS is 'Darwin'(Mac), speak the word.
if [[ ${is_speakable} = true \
&& $(uname) =~ Darwin* \
&& ${#meanings[@]} > 0 ]]; then
say "${word}" 2> /dev/null # ignore if error occurred
fi
}
print_help () {
cat <<MSG
Usage: ndic [-hds] <word>
Description:
Find the meaning of <word> in English-Korean Dictionary.
(Powered by Naver)
Options:
-h Show help message
-d Turn on debug mode
-s Speak the word
-c Search by clipboard contents
Examples:
$ ndic nice
[형용사](기분) 좋은, 즐거운, 멋진
[명사]니스 ((프랑스 남동부의 피한지))
$ ndic "good thing" # use quotes if a word has spaces
[구어] 좋은 일; 좋은 착상; 행운; 경구; 진미; 사치품
$ ndic -s nice # search and speak the word
$ ndic -c # search by clipboard contents
MSG
}
main "$@"