python 使用OSX Dictionary API Python绑定来获取单词的字典定义(并将其着色)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 使用OSX Dictionary API Python绑定来获取单词的字典定义(并将其着色)相关的知识,希望对你有一定的参考价值。
#!/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.OKGREEN + r'\1' + bcolors.ENDC, result)
result = re.sub(r'▶([^\s]+)', '\n\n ' + bcolors.FAIL + '▶ ' + bcolors.OKGREEN + r'\1' + bcolors.ENDC + '\n ', result)
result = re.sub(r'• (\b[A-Z][a-z]+\b)', '\n ' + bcolors.FAIL + '• ' + bcolors.OKGREEN + r'\1' + bcolors.ENDC, result)
result = re.sub(r'• (\b[a-z]+\b)', '\n ' + bcolors.FAIL + '• ' + bcolors.ENDC + r'\1', result)
result = re.sub(r'([^\dA-Za-z])(\d) ([^|])', r'\n \1' + bcolors.FAIL + r'\2 ' + bcolors.ENDC + r'\3', result)
result = re.sub(r'(DERIVATIVES|ORIGIN|PHRASES) ', '\n\n ' + bcolors.OKGREEN + r'\1\n ' + bcolors.ENDC, result)
result = re.sub(r'\|([^|\n,.]{2,50})\|', bcolors.HEADER + r'/\1/' + bcolors.ENDC, result)
result = re.sub(r'(‘|“)(.+?)(’|”)', bcolors.WARNING + r'“\2”' + bcolors.ENDC, result)
print result
if __name__ == '__main__':
main()
以上是关于python 使用OSX Dictionary API Python绑定来获取单词的字典定义(并将其着色)的主要内容,如果未能解决你的问题,请参考以下文章
使用Python Dictionary在Python中合并CSV文件
python---dictionary字典
Python Dictionary:如何使用单独的字典键更新字典值,基于键
在Python中,何时使用Dictionary,List或Set?
[Python3]Dictionary(字典)
python之字典(Dictionary)