I have a for loop that retrieves bigram data of a page of text from an SQLite3 database.
def bigram_db():
cursr.execute("SELECT * FROM trainedGrammar")
data = cursr.fetchall()
for data in data:
element = data
txt = element[0] #fetch first element of list
txt += txt
return txt
I tried using txt += txt but this only gives me a single paragraph worth bigram data when I tried to print cache outside the function bigram_db(). So how do I store all of the bigram data that is going to be output by the for loop, which can be accessed outside of the for loop and then when I print it, I want the entire bigram data of the database to be available.
You don't need to execute fetchall()
, you can iterate directly on the cursor. And you cannot use the same variable txt
for two purposes; in the loop, the line txt = element[0]
overwrites its old value.
Your function should look like this:
def bigram_db():
cursr.execute("SELECT * FROM trainedGrammar")
txt = ""
for row in cursr:
txt += row[0]
return txt
Or without a for loop:
def bigram_db():
cursr.execute("SELECT * FROM trainedGrammar")
return "".join([row[0] for row in cursr])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.