1

I wrote a simple script for translation in urbandictionary:

import urllib.request
import bs4

def translate():
    search=''
    while(search!='!'):
        search=input("Enter a word(! for exit): ")
        if search=='!':
            continue
        search2=search.replace(' ','+')
        urb_url='http://www.urbandictionary.com/define.php?term='+str(search2)
        urban=urllib.request.urlopen(urb_url).read().decode('utf-8')
        soup_urb = bs4.BeautifulSoup(urban)
        try:
            q2=soup_urb.find('div', class_="meaning").text
            print("{0}: {1}".format(search,q2))
        except AttributeError as e:
            print("The word not found\n")

now I want to save result for every word that searched to use and don't search again in the future. what is your suggestion? sqlite, save in simple text or other solutions.

2 Answers 2

5

You can use sqlite3 or whatever any database. Try this

import sqlite3

conn = sqlite3.connect('test.db')
try:
    conn.execute('''CREATE TABLE urbandictionary
           (SEARCH_WORD TEXT NOT NULL,
           SEARCH_STRING TEXT NOT NULL)''')
    print "Table created successfully";
except:
    pass

conn.close()

Then in your print statement line, put

conn = sqlite3.connect('test.db')
conn.execute("INSERT INTO urbandictionary (SEARCH_WORD, SEARCH_STRING) \
      VALUES (?,?)", [search, q2])
conn.commit()
conn.close()

To view the results,

conn = sqlite3.connect('test.db')
cur = conn.execute('select * from urbandictionary')
res = [dict(search_word=row[0], search_string=row[1]) for row in cur.fetchall()]
conn.close()

>>>res #gives you output
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for your code. but what if i want to see a word is in database or not? and show that word from database
conn.execute("select * from urbandictionary where SEARCH_WORD like '%"+"searchword"+"%'")
2

SQLite is a good way to do it if you plan to add functionalities to your application or if the amount of data can grow big: you will be able to add tables to your database and/or process usefull SQL requests.

However it adds complexity to your architecture: use of a database, use of SQL requests.

You could as well use a dictionary with keys being 'search' and values being 'q2' and store it with the pickle module (Python object serialization). That way you can keep it quite simple if your purpose is only to store and get translations back.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.