2016-09-22 199 views
0

如何解析Fruit Basket中的逗號分隔值並將它們移動到其他列。如何將SQLite列中的分隔值拆分爲多列

例如,我想這

Fruit Basket Fruit1 Fruit2 Fruit3 
------------ -------- -------- -------- 
Apple 
Banana, Pear 
Lemon, Peach, Apricot 

這個

Fruit Basket Fruit1 Fruit2 Fruit3 
------------ -------- -------- -------- 
Apple   Apple 
Banana, Pear Banana Pear 
Lemon, Pea... Lemon  Peach  Apricot 

如果我不能做到這一點與純SQLite的說法,我怎麼能做到這一點使用Python變?

+0

你是說你的'水果籃'列已經存儲逗號分隔的字符串?它是如何到達那裏的? – Falmarri

+0

是的,該列已經存儲了彗形分離的字符串。該列在預先存在的數據庫中以這種方式出現。 –

+0

你總是保證1到3個水果?如果沒有,我不確定柱狀數據庫是否是這個最好的主意 –

回答

0

檢查手冊頁:

man sqlite3 | less +/-csv 

然後使用

sqlite ... -csv | ... 

輸出將被退出更容易解析

0

拉開一列是爲Python非常簡單(不確定關於SQLite)。這將您的DB行簡化爲一個字符串數組,並且應該與SQLite返回類似。

text = [ 
    'Apple', 
    'Banana, Pear', 
    'Lemon, Peach, Apricot' 
] 

for line in text: 
    cols = [c.strip() for c in line.split(',')] 
    print(cols) 

應該輸出每串線陣列:

['Apple'] 
['Banana', 'Pear'] 
['Lemon', 'Peach', 'Apricot'] 

編輯:

這裏有一個完整的Python腳本,做你想找什麼樣的SQLite的:

import sqlite3 

conn = sqlite3.connect('test.db') 
c = conn.cursor() 
c.execute(
    '''SELECT * 
      FROM Fruits 
      WHERE Fruit_Basket IS NOT NULL''' 
) 
rows = c.fetchall() 
for row in rows: 
    fruit_basket = row[0] 
    fruits = [f.strip() for f in fruit_basket.split(',')] 
    while (len(fruits) < 3): 
     fruits.append('') 
    print(fruits) 
    update = '''UPDATE Fruits 
        SET Fruit1 = ?, Fruit2 = ?, Fruit3 = ? 
        WHERE Fruit_Basket = ?''' 
    c.execute(update, fruits + [fruit_basket,]) 
conn.commit() 
conn.close() 
+0

正確...我用這個語句得到了這個聲明'cursor.execute(「UPDATE table SET Fruit1 = function(FruitBasket,0)WHERE FruitBasket IS NOT NULL;」)'在哪裏僞代碼'function(FruitBasket,0)'將水果名稱字符串拆分成一個列表,並返回索引0處的第一個字符串...希望這是可能的 –

0

明白了吧

def returnFruitName(string, index): 
    #Split string and remove white space 
    return [x.strip() for x in string.split(',')][index] 


cur.create_function("returnFruitName", 2, returnFruitName) 

cur.execute("UPDATE t SET Fruit1 = returnFruitName(FruitBasket,0) WHERE FruitBasket IS NOT NULL;") 
cur.execute("UPDATE t SET Fruit2 = returnFruitName(FruitBasket,1) WHERE FruitBasket IS NOT NULL;") 
cur.execute("UPDATE t SET Fruit3 = returnFruitName(FruitBasket,1) WHERE FruitBasket IS NOT NULL;")