简体   繁体   English

如何使用Python将逗号分隔的值分成多行

[英]How to split comma delimited values into multiple rows using Python

I'm using Python and SQLite to manipulate a database. 我正在使用Python和SQLite来操作数据库。

I have an SQLite Table Movies that looks like this: 我有一个看起来像这样的SQLite Table Movies

| ID             | Country     
+----------------+-------------
| 1              | USA, Germany, Mexico 
| 2              | Brazil, Canada
| 3              | Peru

I would like to split the comma delimited values in Country and insert them into another table Countries so that Countries table looks like this 我想在“ Country拆分逗号分隔的值,并将其插入到另一个表“ Countries这样“ Countries表看起来像这样

| ID             | Country     
+----------------+-------------
| 1              | USA
| 1              | Germany
| 1              | Mexico
| 2              | Brazil
| 2              | Canada
| 3              | Peru

How do I do split the values from Country column in Movies table and insert them into Country column in Countries table? 如何从“ Movies表中“ Country列中拆分值,然后将其插入“ Country表中的“ Countries Country列中?

According to this post , I can't accomplish this task using pure SQLite. 根据这篇文章 ,我无法使用纯SQLite完成此任务。 How would I go about it using Python? 我将如何使用Python进行处理?

Using Python, 使用Python,

cursor.execute("""Select * from Movies""")
all_data = cursor.fetchall()
cursor.execute("""CREATE TABLE IF NOT EXISTS Countries
                    (ID TEXT,
                    Country TEXT)""")
for single_data in all_data:
    countries = single_data[1].split()
    for single_country in countries:
        cursor.execute("""INSERT INTO Countries VALUES(%s,"%s")"""%(single_data[0],single_country))
    conn.commit()

You can solve this in pure SQLite using a common table expression. 您可以使用通用表表达式在纯SQLite中解决此问题。

create table movies(id integer primary key, country text);
insert into movies values
(1,'USA, Germany, Mexico'), (2,'Brazil, Canada'), (3,'Peru');

create table countries(id integer, country text);
insert into countries
WITH split(id, country, str) AS (
    SELECT id, '', country||',' FROM movies
    UNION ALL SELECT id,
    trim(substr(str, 0, instr(str, ','))),
    substr(str, instr(str, ',')+1)
    FROM split WHERE str!=''
) SELECT id, country FROM split WHERE country!='' ORDER BY id;

SELECT * FROM countries;

id|country
1|USA
1|Germany
1|Mexico
2|Brazil
2|Canada
3|Peru

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM