2016-09-22 198 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;")