19

Is there a bash or applescript to look up a word in /Applications/Dictionary.app from a Terminal window ?

open -a /Applications/Dictionary.app/ --args word

ignores --args, says "type a word to look up"

Mac Dictionary improvements suggests ⌃ Control ⌘ Command D however I'm looking to launch the full app, not just the small popover.

20

You can use...

open dict://my_word

...which will open the Dictionary application and lookup the string my_word. If you want to use multiple words use something like open dict://"Big Bang Theory".

There's no output in the Terminal though.

  • Thanks. Is there a list of open magicprefix:... someplace ? – denis Apr 29 '13 at 11:16
  • @Denis I don't know of a source that specifically collects undocumented command options for open. But generally speaking, hints.macworld.com is a well known source for hidden gems. I also used to know a different source which collects undocumented defaults write commands, but I can't remember it just know and Google did not help me either... – gentmatt Apr 29 '13 at 11:37
  • I made a brief summary of open on SuperUser a while ago superuser.com/questions/4368/os-x-equivalent-of-windows-run-box/… – Josh Hunt Apr 30 '13 at 12:16
  • @denis the system maintains a database of all the prefixes that all the apps installed have told it how to handle. If you can think of a practical use for knowing that tidbit, asking a full question would be awesome. – bmike May 5 '13 at 14:12
18

Using the Python Objective-C bindings, you could create just a small python script to get it from the built in OS X Dictionary. Here's a post that details this script"

#!/usr/bin/python

import sys
from DictionaryServices import *

def main():
    try:
        searchword = sys.argv[1].decode('utf-8')
    except IndexError:
        errmsg = 'You did not enter any terms to look up in the Dictionary.'
        print errmsg
        sys.exit()
    wordrange = (0, len(searchword))
    dictresult = DCSCopyTextDefinition(None, searchword, wordrange)
    if not dictresult:
        errmsg = "'%s' not found in Dictionary." % (searchword)
        print errmsg.encode('utf-8')
    else:
        print dictresult.encode('utf-8')

if __name__ == '__main__':
    main()

Save that to dict.py, and then just run python dict.py dictation

enter image description here

Check out the post for more instructions on making it accessable all across your terminal.

  • 1
    I used this script, but there is no line break in the output, it looks like this: i.imgur.com/ooAwQCA.png (on an OS X 10.9). – h__ Mar 23 '15 at 19:23
  • I also get no newline in the output. Checking print repr(dictresult.encode('utf-8')) shows me this: 'dictation |d\xc9\xaak\xcb\x88te\xc9\xaa\xca\x83(\xc9\x99)n| \xe2\x96\xb6noun [ mass noun ] 1 the action of dictating words to be typed, written down, or recorded on tape: the dictation of letters. \xe2\x80\xa2 the activity of taking down a passage that is dictated by a teacher as a test of spelling, writing, or language skills: passages for dictation. \xe2\x80\xa2 words that are dictated: the job will involve taking dictation, drafting ...' – nnn Sep 19 '15 at 9:37
  • I've added some string replacements to simulate line breaks.. seems to work ok although I haven't tested it extensively: gist.github.com/lambdamusic/bdd56b25a5f547599f7f – magicrebirth Nov 12 '15 at 12:02
  • This doesn't seem to work anymore. – Toothrot Mar 27 '16 at 18:20
4

I was also going to suggest open dict://word, but Google's dictionary API also uses the New Oxford American Dictionary:

#!/usr/bin/env ruby

require "open-uri"
require "json"
require "cgi"

ARGV.each { |word|
  response = open("http://www.google.com/dictionary/json?callback=dict_api.callbacks.id100&q=#{CGI.escape(word)}&sl=en&tl=en&restrict=pr,de").read
  results = JSON.parse(response.sub(/dict_api.callbacks.id100\(/, "").sub(/,200,null\)$/, ""))
  next unless results["primaries"]
  results["primaries"][0]["entries"].select { |e| e["type"] == "meaning" }.each { |entry|
    puts word + ": " + entry["terms"][0]["text"].gsub(/x3c\/?(em|i|b)x3e/, "").gsub("x27", "'")
  }
}
  • 1
    That Google API is deprecated and returns 404. Looks like dictionaryapi.com could work, just have to make a login. – Sam Berry Apr 10 '16 at 18:26
4

I found a solution using Swift 4.

#!/usr/bin/swift
import Foundation

if (CommandLine.argc < 2) {
    print("Usage: dictionary word")
}else{
    let argument = CommandLine.arguments[1]
    let result = DCSCopyTextDefinition(nil, argument as CFString, CFRangeMake(0, argument.count))?.takeRetainedValue() as String?
    print(result ?? "")
}
  1. save this as dict.swift
  2. add permission by chmod +x dict.swift
  3. lookup dictionary
    • run with interpreter ./dict.swift word
    • build by compiler swiftc dict.swift and run ./dict word
2

The updated code from David Perace answer, add some colors and new lines:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import re
from DictionaryServices import *

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

def main():
    try:
        searchword = sys.argv[1].decode('utf-8')
    except IndexError:
        errmsg = 'You did not enter any terms to look up in the Dictionary.'
        print errmsg
        sys.exit()
    wordrange = (0, len(searchword))
    dictresult = DCSCopyTextDefinition(None, searchword, wordrange)
    if not dictresult:
        errmsg = "'%s' not found in Dictionary." % (searchword)
        print errmsg.encode('utf-8')
    else:
        result = dictresult.encode('utf-8')
        result = re.sub(r'\|(.+?)\|', bcolors.HEADER + r'/\1/' + bcolors.ENDC, result)
        result = re.sub(r'▶', '\n\n ' + bcolors.FAIL + '▶ ' + bcolors.ENDC, result)
        result = re.sub(r'• ', '\n   ' + bcolors.OKGREEN + '• ' + bcolors.ENDC, result)
        result = re.sub(r'(‘|“)(.+?)(’|”)', bcolors.WARNING + r'“\2”' + bcolors.ENDC, result)
        print result

if __name__ == '__main__':
    main()
1

Try Dictionary OSX (I made this after getting stuck with other answers and wanting a non-Python solution). It uses the definitions from Dictionary.app.

dictionary cat
# cat 1 |kat| ▶noun 1 a small domesticated carnivorous mammal with soft fur...

It uses DictionaryKit, a wrapper for the private Dictionary Services available on OSX. There's interesting background information about how this works on NSHipster.

1

checkout this github repo: https://github.com/aztack/osx-dictionary

install: brew install https://raw.githubusercontent.com/takumakei/osx-dictionary/master/osx-dictionary.rb --HEAD

enter image description here

0

I came across this post looking for a similar thing. Wasn't happy with the options available so made simple script. Its a terminal based thesaurus with text to speech. May be of interest ...

https://github.com/aefty/thes

0

Look in the following thread to find out how to use Dictionary.app in the Terminal: https://discussions.apple.com/thread/2679911?start=0&tstart=0

  • 1
    Answers on Ask Different need to be more than just a link. It's okay to include a link, but please summarize or excerpt it in the answer. The idea is to make the answer stand alone. – nohillside Nov 7 '15 at 17:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .