Python 如何将文本拆分为逗号后跟空格,而不是空格后跟数字?
大家好,我正试图在python3中用逗号分割DDL,但问题是像'numeric1,1'或'decimal2,4'甚至'identity1,2'这样的数据类型给我带来了困难 这是输入:Python 如何将文本拆分为逗号后跟空格,而不是空格后跟数字?,python,sql,regex,Python,Sql,Regex,大家好,我正试图在python3中用逗号分割DDL,但问题是像'numeric1,1'或'decimal2,4'甚至'identity1,2'这样的数据类型给我带来了困难 这是输入: ['x int not null, y decimal(2, 4) null, z numeric(7, 3), m bigint identity(1,1), d date] 这就是我想要的输出: ['x int not null','y decimal(2, 4) null','z numeric(7, 3)
['x int not null, y decimal(2, 4) null, z numeric(7, 3), m bigint identity(1,1), d date]
这就是我想要的输出:
['x int not null','y decimal(2, 4) null','z numeric(7, 3)','m bigint identity(1,1)','d date']
然后我将其按空间分割,并可以处理我的代码
如果我使用list.split',它也会按小数点逗号和标识进行拆分
编辑:逗号问题解决后,我有不同的问题
嗨,我有这个清单:
['x int not null','y decimal2,4 null','z numeric7,3','m bigint identity1,1','d date']
我想得到mo for循环中每个迭代的输出:
['x'、'int'、'not'、'null']
['y'、'decimal2,4'、'null']
等等
当我按空间分割时,我得到:
['x'、'int'、'not'、'null']
['y'、'decimal2'、'4'、'null']
我这样做是因为我想在拆分[1]后处理列表,这是数据类型,但我想将所有数字2、4作为一个单元格,而不是小数2和4
如何用不跟数字的空格分割?用逗号分割,后跟空格,不跟数字,然后:
我会使用正则表达式来实现这个目的,我认为这样的东西应该可以工作:
import re
my_list = ['x int not null, y decimal(2, 4) null, z numeric(7, 3), m bigint identity(1,1), d date']
result = re.split(r',\s*(?![^()]*\))', my_list[0])
# result => ['x int not null', 'y decimal(2, 4) null', 'z numeric(7, 3)', 'm bigint identity(1,1)', 'd date']
它将使用负前瞻来匹配所有不在括号中的字符
一旦获得结果,请循环浏览并以任何需要的方式进行处理:
for item in result:
# split items more if needed:
res = re.split(r' \s*(?![^()]*\))', item)
print(res)
伟大的现在我有另一个问题。。在我得到这个列表后,我想用空格分开。。['x int not null','y decimal2,4 null','z numeric7,3','m bigint identity1,1','d date']如果我在数字空间中有一个数字后面,那么它的应用程序也是。。我想避免将这种情况拆分为数字'2,4'。。我该怎么做?@Pythonist我更新了我的答案,但如果这个或其他答案解决了您当前的问题,请接受您认为最有用的答案之一。至于其他问题,要么自己解决,要么问另一个问题!我会问另一个问题嗨,我有一个列表:['x int not null',y decimal2,4 null',z numeric7,3',m bigint identity1,1',d date'],我想在mo for循环中得到每个迭代的输出:['x','int','not','null']['y','decimal2,4',null']等等。。。当我按空间分割时,我得到:['x'、'int'、'not'、'null']['y'、'decimal2'、'4'、'null']我这样做是因为我不想在分割后处理列表[1]这是数据类型,但我想把所有的数字2、4作为一个单元格,而不是作为'decimal2'和'4'如何分割成一个不跟数字在后面的空间?@Pythonist我更新了我的答案,检查这是否解决了您的问题。此外,请避免使用附加要求更新原始问题,如果特定问题已解决,请使用复选标记✓ 在答案旁边,这有助于接受它作为解决方案。如果您在初始问题解决后遇到其他问题,请随意创建一个新问题,而不是更新原始问题。您好,我有以下列表:['x int not null','y decimal2,4 null','z numeric7,3','m bigint identity1,1','d date'],并且我希望在mo for循环中为每个迭代获得此输出:[x'、'int'、'not'、'null'][y'、'decimal2,4'、'null']等等……当我用空格拆分时,我得到:['x'、'int'、'not'、'null'][y'、'decimal2'、'4'、'null']我这样做是因为我不想在拆分后处理列表[1]这是数据类型,但我想将所有数字2、4作为一个单元格,而不是“小数2”和“4”,如何用不后跟数字的空格分割?这是对我的答案的评论吗?是的,保罗,你说得对。如果你有不同的问题,请打开另一个。如果这里的任何其他答案解决了这个原始问题,请查看解决方法做
for item in result:
# split items more if needed:
res = re.split(r' \s*(?![^()]*\))', item)
print(res)