[英]Split by comma and how to exclude comma from quotes in split in python
I am struggling to split this string on the basis of comma but comma inside the double quotes should be ignored.我正在努力根据逗号拆分此字符串,但应忽略双引号内的逗号。
cStr = 'aaaa,bbbb,"ccc,ddd"'
expected result : ['aaaa','bbbb',"ccc,ddd" ]
please help me, I tried different methods as mentioned in below soln but couldn't resolve this issue [I am not allowed to use csv, pyparsing module]请帮助我,我尝试了以下解决方案中提到的不同方法,但无法解决此问题 [我不允许使用 csv,pyparsing 模块]
there is already similar question asked before for the below input.之前已经针对以下输入提出了类似的问题。
cStr = '"aaaa","bbbb","ccc,ddd"'
result = ['"aaa"','"bbb"','"ccc,ddd"']
The usual way I handle this is to use a regex alternation which eagerly matches double quoted terms first, before non quoted CSV terms:我处理此问题的常用方法是使用正则表达式替换,它首先热切匹配双引号术语,然后是未引用的 CSV 术语:
import re
cStr = 'aaaa,bbbb,"ccc,ddd"'
matches = re.findall(r'(".*?"|[^,]+)', cStr)
print(matches) # ['aaaa', 'bbbb', '"ccc,ddd"']
You could use list comprehension, no other libraries needed:您可以使用列表理解,不需要其他库:
cStr = 'aaaa,bbbb,"ccc,ddd"'
# split by ," afterwards by , if item does not end with double quotes
l = [
item.split(',') if not item.endswith('"') else [item[:-1]]
for item in cStr.split(',"')
]
print(sum(l, []))
Out:出去:
['aaaa', 'bbbb', 'ccc,ddd']
This can be achieved in three steps-这可以通过三个步骤来实现-
cstr = 'aaaa,bbbb,"ccc,ddd","eee,fff,ggg"'
Step 1-步骤1-
X = cstr.split(',"')
Step 2-第2步-
regular_list = [i if '"' in i else i.split(",") for i in X ]
Step 3-步骤 3-
final_list = []
for i in regular_list:
if type(i) == list:
for j in i:
final_list.append(j)
else:
final_list.append('"'+i)
Final output -最终 output -
['aaaa', 'bbbb', '"ccc,ddd"', '"eee,fff,ggg"']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.