I've been reading Python tutorials since I accidentally see the Zen of Python. I think I read enough. Now its time to get hands dirty. The best way to learn a language is to write code in that language. I have implemented a command line dictionary that fetches the Turkish definition of a given English word from the site Sesli Sözlük. The python script below uses BeautifulSoup HTML/XML parser for screen-scraping.
This is sozluk.py. It reads program arguments and constructs a URL. After fetching URL content BeatifulSoup library is used to get desired parts of the HTML page. Finally results are printed to the stdout.
This is sozluk.sh. It is used to call Python Interpreter and execute sozluk.py.
An example usage: Getting Turkish definition of word 'python'
This is sozluk.py. It reads program arguments and constructs a URL. After fetching URL content BeatifulSoup library is used to get desired parts of the HTML page. Finally results are printed to the stdout.
from BeautifulSoup import BeautifulSoup
import urllib2
import sys
import string
def getDefinitions(keyword):
url = 'http://www.seslisozluk.com/?word='+keyword
c=urllib2.urlopen(url)
soup=BeautifulSoup(c.read())
results = soup.findAll(attrs={"class" : "dict_result"})[0].contents[1].contents
definitions = [results[x] for x in range(len(results)) if ((x+2)%3)==0]
return [definition.replace(' ', '') for definition in definitions]
if __name__ == '__main__':
if len(sys.argv)<=1:
print 'missing keyword.'
else:
keyword =' '.join(sys.argv[1:])
try:
definitions = getDefinitions(keyword)
for i in definitions:
print i
except:
print "Failed to get definition of ",keyword
This is sozluk.sh. It is used to call Python Interpreter and execute sozluk.py.
#!/bin/bash
#sozluk.py is in this folder.
cd /home/ilkinulas/PITON/workspace
python sozluk.py $1
An example usage: Getting Turkish definition of word 'python'
ilkinulas@tututil:~/PITON$ sozluk.sh python
Bir proglama dili.
i., zool. piton. piton yilani. yılan. yılan. i., zool. piton. apollon'un öldürdüğü dev yılan. piton.
Delfi civarında Apollon tarafından öldürülmüş olan çok büyük bir yılan; piton, k, Python, piton, h, zool.
: Gaia'nın doğurduğu efsanevi yılan. Yüz tane başı, alev kusan yüz tane ağazı vardı. Apollon tarafından öldürüldü.
piton yılanı.
piton yılanı.
yılan.
0 comments:
Post a Comment