Question

I have created a sql file with python inserting some data from a imdb.txt file.

My code so fare:

import re
import sqlite3
conn = sqlite3.connect('imdb1.db')
c = conn.cursor()

c.execute('''CREATE TABLE imdb1 (ROWID INTEGER PRIMARY KEY, Title, Rating)''')

x = open("ratings.list.txt","r")
movread = x.readlines()
x.close()



s = raw_input('Search: ').lower()
for ns in movread:


    if s in ns.lower():
        d = re.split('\s+',ns,4)
        Title = d[4].rstrip()
        Rating= d[3]

        list = [Title,Rating]

       # print list
        # Insert a row of data
        c.execute('INSERT INTO imdb1 ( Title, Rating) values (?, ?)', (list[0],list[1]))
        conn.commit()

for row in c.execute('SELECT * FROM imdb1 order by ROWID'):
       print row

This is the output when i print the row:

ROWID                       Title                            Rating

(1, u'The Lord of the Rings: The Return of the King (2003)', u'8.9')
(2, u'The Lord of the Rings: The Fellowship of the Ring (2001)', u'8.8')
(3, u'The Lord of the Rings: The Two Towers (2002)', u'8.7')
(4, u'"5 Second Movies" (2007) {The Lord of the Rings and the Two Towers (#1.63)}', u'6.2')

I want to get all the titles in one list. Like this:

Note that the IMDB file is huge so this is like 0.1% of the output

 ( u'The Lord of the Rings: The Return of the King (2003)',
    u'The Lord of the Rings: The Fellowship of the Ring (2001)',
    u'The Lord of the Rings: The Two Towers (2002)',
    u'"5 Second Movies" (2007) {The Lord of the Rings and the Two Towers (#1.63)}')

Can i somehow do this with sql or some basic python?

Was it helpful?

Solution

As you iterate through your rows the title is going to be an item you can reference from the tuple - if you just want to print it use

print row[1]

If you want to collect all titles in a python list,

titleList = []
....
for row in c.execute('SELECT * FROM imdb1 order by ROWID'):
    titleList.append(row[1])

You could also change your SELECT statement from "SELECT * ..." to "SELECT Title" if all you want is titles, which will make the Title value the only item in the row (at row[0]).

Caveat, I'm not sure about the column headings that are printing out there, or about the last row in the example of what you want which looks like more than just a title.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top