How to look up strange words in Terminal
February 18th, 2010
3 comments
The following python script which is aiming for translating English words to Chinese runs perfectly on Mac Terminal:
Comments: This version requires that the data(String) has a integral xml structure.
#! /usr/bin/python
import re,urllib,sys
import xml.dom.minidom
from xml.dom.minidom import Node
url=”http://dict-co.iciba.com/api/dictionary.php?w=”
if len( sys.argv ) > 1:
url +=sys.argv[1]
else :
print “please input your searching word…”
sys.exit(1)
file=urllib.urlopen( url )
content = file.read()
file.close()
doc = xml.dom.minidom.parseString( content )
acceptation=”"
for node in doc.getElementsByTagName(“acceptation”):
for node1 in node.childNodes:
if node1.nodeType == Node.TEXT_NODE:
acceptation += node1.data+”\n”
print re.sub( ‘\\n$’,”, acceptation )
import re,urllib,sys
import xml.dom.minidom
from xml.dom.minidom import Node
url=”http://dict-co.iciba.com/api/dictionary.php?w=”
if len( sys.argv ) > 1:
url +=sys.argv[1]
else :
print “please input your searching word…”
sys.exit(1)
file=urllib.urlopen( url )
content = file.read()
file.close()
doc = xml.dom.minidom.parseString( content )
acceptation=”"
for node in doc.getElementsByTagName(“acceptation”):
for node1 in node.childNodes:
if node1.nodeType == Node.TEXT_NODE:
acceptation += node1.data+”\n”
print re.sub( ‘\\n$’,”, acceptation )
This version is more robust and fast:
#! /usr/bin/python
import urllib,sys
url=”http://dict-co.iciba.com/api/dictionary.php?w=”
if len( sys.argv ) > 1:
url +=sys.argv[1]
else :
print “please input your searching word…”
sys.exit(1)
file=urllib.urlopen( url )
content = file.read()
file.close()
acceptation=”"
arr=()
content=content.partition(“<acceptation>”)[2]
while content :
arr = content.partition(“</acceptation>”)
acceptation +=arr[0] + “\n”
content = arr[2].partition(“<acceptation>”)[2]
import urllib,sys
url=”http://dict-co.iciba.com/api/dictionary.php?w=”
if len( sys.argv ) > 1:
url +=sys.argv[1]
else :
print “please input your searching word…”
sys.exit(1)
file=urllib.urlopen( url )
content = file.read()
file.close()
acceptation=”"
arr=()
content=content.partition(“<acceptation>”)[2]
while content :
arr = content.partition(“</acceptation>”)
acceptation +=arr[0] + “\n”
content = arr[2].partition(“<acceptation>”)[2]
print acceptation.rstrip(‘\n’)
How to use it:
Requirements: Unix based system, Python installed, Internet connected
the file is named “dict” and given the permission 755.
when starting terminal, I always run the command alias dict=your path/dict
then you can test: dict Hello, the result will be 喂, 哈罗.
Recent Comments