Apple Event: May 7th at 7 am PT

Looks like no one’s replied in a while. To start the conversation again, simply ask a new question.

Using dictionary from command line

Is it possible I could see the definition of a word for eg. 'Apple' in terminal itself without opening the dictionary app?

I work in the terminal most of the times and I am just wondering if I could get all the information in terminal itself.

Any ideas? Thanks!

Message was edited by: kt.kthapar

iMac 27' Quadcore, Mac OS X (10.6.4)

Posted on Dec 11, 2010 6:04 AM

Reply
40 replies

Nov 1, 2015 7:02 AM in response to Roote

I have posted Python and Ruby code to the communities in the past, that was syntax, format, and runtime correct on my end. In the support communities, I have used plain text (posting directly into the article), placed the code within an inserted quote, or various syntax highlighting choices from the advanced editor, and the code did not remain true to the same format as it was on my Mac.


The following Python code contains no tabs, and all indented code is in 4-space multiples. This was done as an exercise to see if you can copy/paste it back to you, and run it without indentation errors. The code when provided a full, or shorthand path to a Word .docx document, will list the fonts that are referenced inside of it. It uses a positive Lookbehind in the regular expression. It is tested on El Capitan 10.11.1, and the default Python 2.7.10 from Apple. I never post code that uses a third-party Python module.

User uploaded fileUser uploaded file


#!/usr/bin/env python

import zipfile

import re

import os

import sys




def main():

fonts = []

try:

thefile = os.path.expanduser(sys.argv[1])

except (ValueError, IndexError):

sys.exit('Usage: {} filename.docx\n'.format(sys.argv[0]))

if not thefile.endswith('.docx'):

sys.exit('Not a valid Word document')

# Word docx compressed-zip, single file format

if zipfile.is_zipfile(thefile):

with zipfile.ZipFile(thefile, 'r') as pzip:

xmldata = pzip.read('word/fontTable.xml')

fonts = re.findall(r'(?<=w:name=)("[ \w+]+")>', xmldata)

for name in fonts:

print("{}".format(name))

if __name__ == '__main__':

sys.exit(main())


Nov 1, 2015 11:50 AM in response to Roote

Looks like tabs and newlines are primarily the risk of retrieving usable code that is indentation dependent. Good that you are using Sublime Text though.


One can replace tabs with exactly four spaces (for posting) by adapting a Sublime Text 3 Preference setting in Settings-User. The following would apply as the last two lines in the user settings file.


"tab_size": 4,

"translate_tabs_to_spaces": true


Ideally, one would create language specific settings files named (e.g. Python.sublime-settings) in the following location:


~/Library/Application Support/Sublime Text 3/Packages/User


PEP 8 E303 is the reason for the main function in your image getting lit up. Wants exactly two blank lines preceding each function definition. The hosting software added one on you. It would also appear that an extra trailing space was added too. Python wants a newline at the end of the file, which is why your line 25 was lit up by a PEP 8 W292.

Nov 2, 2015 10:45 AM in response to VikingOSX

Sublime Text is an excellent tool, especially for indentation dependent code. Thanks for the tip regarding tabs to spaces, a nice time saver. Here's dict.py and dictbox.py in Sublime Text:

User uploaded file User uploaded file

I suppose an option, given the code sharing vagaries of the hosting service, is to use a file sharing service to provide a download link. With that in mind, here are Dropbox links for previewing the code and downloading:


dict.py

dictbox.py

User uploaded file

User uploaded file

Tested with:


OS X El Capitan 10.11, Python 2.7.10

OS X Yosemite 10.10.5, Python 2.7.10

OS X Mavericks 10.9.5, Python 2.7.5

Nov 2, 2015 2:58 PM in response to kt.kthapar

Hello


I know this is so very late reply but anyway here's my version of pyobjc code which works under OS X 10.6.8. Since pyobjc bridgesupport file for DictionaryServices.framework is broken under OS X 10.6.8, fixed bridgesupport metadata is loaded manually here. Don't know whether this should work under later OSes.



#!/usr/bin/python # coding: utf-8 import sys, objc from CoreFoundation import * DCS_BRIDGESUPPORT = '''<?xml version="1.0" standalone="yes"?> <!DOCTYPE signatures SYSTEM "file://localhost/System/Library/DTDs/BridgeSupport.dtd"> <signatures version="0.9"> <function name="DCSCopyTextDefinition"> <arg type="^{__DCSDictionary=}"></arg> <arg type="^{__CFString=}"></arg> <arg type64="{_CFRange=qq}" type="{_CFRange=ii}"></arg> <retval type="^{__CFString=}"></retval> </function> </signatures>''' objc.parseBridgeSupport( DCS_BRIDGESUPPORT, globals(), objc.pathForFramework('/System/Library/Frameworks/CoreServices.framework/Frameworks/DictionaryServices.framework') ) for q in [ e.decode('utf-8') for e in sys.argv[1:] ]: r = DCSCopyTextDefinition(None, q, (0, len(q))) print '[%s]\n%s' % tuple( [e.encode('utf-8') for e in [q, r or 'nil\n']] )




Tested with pyobjc 2.2b3 and python 2.6.1 under OS X 10.6.8.


Cheers,

H

Nov 4, 2015 2:07 PM in response to VikingOSX

Hello VikingOSX,


Thank you for testing it. It is indeed very good news that manual loading of bridgesupport metadata still works with recent pyobjc, for it opens straightforward door to undocumented framework functions without resorting to ctypes module.


Regarding DictionaryServices.framework, more comlpicated and finer queries are possible by using undocumented functions as shown in the following threads. Now those rubycocoa codes may be translated into pyobjc codes without much difficulty.


How can I use Automator to extract substring of text based on pattern?

https://discussions.apple.com/thread/6525478


Results from OpenThesaurus as a Service: How?

https://discussions.apple.com/thread/6616776



---

By the way, here's a revision of my script which incorporated textwrap feature inspired by Roote. 🙂



#!/usr/bin/python # coding: utf-8 # # file: # dict.py # # usage: # ./dict.py hippopotamus rhinoceros 人 佛 # # version: # 0.20 # - added textwrap feature # 0.15 # - manually loading fixed bridgesupport metadata # # written by Hiroto, 2015-11 # import sys, objc import textwrap from CoreFoundation import * DCS_BRIDGESUPPORT = '''<?xml version="1.0" standalone="yes"?> <!DOCTYPE signatures SYSTEM "file://localhost/System/Library/DTDs/BridgeSupport.dtd"> <signatures version="0.9"> <function name="DCSCopyTextDefinition"> <arg type="^{__DCSDictionary=}"></arg> <arg type="^{__CFString=}"></arg> <arg type64="{_CFRange=qq}" type="{_CFRange=ii}"></arg> <retval type="^{__CFString=}"></retval> </function> </signatures>''' objc.parseBridgeSupport( DCS_BRIDGESUPPORT, globals(), objc.pathForFramework('/System/Library/Frameworks/CoreServices.framework/Frameworks/DictionaryServices.framework') ) for q in [ e.decode('utf-8') for e in sys.argv[1:] ]: r = DCSCopyTextDefinition(None, q, (0, len(q))) or 'nil' r = ' '.join(r.split()) r = textwrap.fill(r, width=48) print '[%s]\n%s\n' % tuple( [e.encode('utf-8') for e in [q, r]] )




All the best,

Hiroto

Nov 4, 2015 2:41 PM in response to Hiroto

And the output on El Capitan 10.11.1 with Python 2.7.10 and standard Apple PyObjc scripting bridge. Appropriate Dictionaries enabled in the Dictionary app preferences.


odin: ~$ hiroto2.py hippopotamus rhinoceros 人 佛

[hippopotamus]

hippopotamus |ˌhɪpəˈpɑdəməs| ▶noun (pl.

hippopotamuses or hippopotami || ) a large

thick-skinned semiaquatic African mammal, with

massive jaws and large tusks. [Family

Hippopotamidae: the very large Hippopotamus

amphibius, frequenting rivers and lakes, and the

smaller pygmy hippopotamus (Choeropsis

liberiensis), frequenting forests near fresh

water in West Africa.] ORIGIN Middle English:

via Latin from Greek hippopotamos, earlier

hippos ho potamios ‘river horse’ (from hippos

‘horse,’ potamos ‘river’).



[rhinoceros]

rhinoceros |raɪˈnɑs(ə)rəs| ▶noun (pl. same or

rhinoceroses) a large, heavily built plant-

eating mammal with one or two horns on the nose

and thick folded skin, native to Africa and

southern Asia. All kinds have become endangered

through hunting. [Family Rhinocerotidae: four

genera and five species.] ORIGIN Middle English:

via Latin from Greek rhinokerōs, from rhis,

rhin- ‘nose’ + keras ‘horn.’



[人]

人 rén①名指由类人猿进化而来的,能思维,能制造并使用工具进行劳动,并能进行语言交际的高等动物

。街上人多 | 男人 | 人类②→名指某种人。证人 | 军人 |

外国人③名指成年人。长大成人④→名别人;他人。舍己救人 |

助人为乐⑤→名指每个人或一般人。人手一册 | 人同此心⑥→名指人手或人才。学校很缺人 |

向社会公开招人⑦→名指人的品质、名声。老冯人很正直 | 丢人现眼⑧→名指人的身体。别把人累坏了

| 人在心不在



[佛]

佛 bì①古同“弼”②○名姓。用法说明除以上意义外,作某些人的名、字时,也读

bì,如佛肸、佛狸。另见 fó;fú。

Nov 8, 2015 10:45 PM in response to KcidKcus

Hi KcidKcus. You're welcome; I glad you found the script(s) useful. I posted revised versions of dict.py and dictbox.py with the same links which you may want to download. They fix some indenting and support for accented letters. No need to revise your ~/.bash_profile, just replace dict.py or dictbox.py in your Scripts folder. Btw, for search terms other than single or hyphenated, use double quotes ("") or escape using the backslash (\). If you copy and paste, a phrase for example, you can paste with the Control-Command-V keys to paste escaped text. Some examples:

User uploaded file

Using dictionary from command line

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple ID.