1

I have a SQLite database that I'd like to find a certain keyword in using Python and display lines of database only containing them in a certain row:

import sqlite3 as lite
con = lite.connect("corpus.db")
c = con.cursor()
keyword = str(input("Which keyword do you wish to find in the corpus? "))
c.execute("SELECT Content FROM Corpus")
#I'm guessing there should be more parameters here

I'm fairly new to coding in general, so sorry if the whole thing seems very noobish. I can't seem to find any similar solutions. I tried doing this (even though it's not exactly what I'm looking for, but I thought I could at least work around with the results from here later):

import sqlite3 as lite
con = lite.connect("corpus.db")
c = con.cursor()
keyword = str(input("Which keyword do you wish to find in the corpus? "))
#For example, "camera"
c.execute("SELECT Content FROM Corpus")
#In my case, content contains a list with this data [('A Japanese woman has been reunited with a camera she dropped in the ocean two-and-a-half years ago, after schoolchildren in Taiwan found it washed up on a beach and covered in barnacles.',), ('The writer is a Washington DC-based foreign affairs analyst. His views are his own.',), ...]
content = c.fetchall()
for text in content:
    if keyword in text:
        print(text)

So, theoretically, it should print the sentence about a Japanese woman, but it prints nothing, so I have no idea what I should do to actually find elements inside of a list even. It works in this example though.

Viktor
  • 13
  • 2

1 Answers1

1

In my case, content contains a list with this data
[('A Japanese woman has been reunited with a camera she dropped in the ocean two-and-a-half years ago, after schoolchildren in Taiwan found it washed up on a beach and covered in barnacles.',), ('The writer is a Washington DC-based foreign affairs analyst. His views are his own.',), ...]

The returned values in content seems to be a list of tuples.
You'll have to iterate again within each tuple to get the sentence.

Like this:

for item in content:
    # item = ('A Japanese woman has been reunited with a camera she dropped in the ocean two-and-a-half years ago, after schoolchildren in Taiwan found it washed up on a beach and covered in barnacles.',)
    for sentence in item:
        if keyword in sentence:
            print(sentence) 
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135