这取决于引用列表元素的’字符.使用此信息时,它仅使用正则表达式拆分未跟随或前置该字符的逗号:
import re
import pandas as pd
import io
text = """TRUE, 93877, S26476961
TRUE, 93878, ['S26489167', 'S26492524']
FALSE, 93879, S26476962
FALSE, 93880, ['S26489168', 'S26492527', 'S26492528']"""
with io.StringIO(text) as f:
for line in f:
print(re.split("(?
# ['TRUE', '93877', 'S26476961']
# ['TRUE', '93878', "['S26489167', 'S26492524']"]
# ['FALSE', '93879', 'S26476962']
# ['FALSE', '93880', "['S26489168', 'S26492527', 'S26492528']"]
# Or with pandas
with io.StringIO(text) as f:
print(pd.read_csv(f,
header=None,
sep="(?
engine='python'))
# 0 1 2
# 0 True 93877 S26476961
# 1 True 93878 ['S26489167', 'S26492524']
# 2 False 93879 S26476962
# 3 False 93880 ['S26489168', 'S26492527', 'S26492528']
编辑:
如果您使用的是python2,则需要将文本转换为unicode(通过将字符u放在文本之前)以便能够使用io.StringIO:
import re
import pandas as pd
import io
text = u"""TRUE, 93877, S26476961
TRUE, 93878, ['S26489167', 'S26492524']
FALSE, 93879, S26476962
FALSE, 93880, ['S26489168', 'S26492527', 'S26492528']"""
with io.StringIO(text) as f:
for line in f:
print(re.split("(?
# ['TRUE', '93877', 'S26476961']
# ['TRUE', '93878', "['S26489167', 'S26492524']"]
# ['FALSE', '93879', 'S26476962']
# ['FALSE', '93880', "['S26489168', 'S26492527', 'S26492528']"]
# Or with pandas
with io.StringIO(text) as f:
print(pd.read_csv(f,
header=None,
sep="(?
engine='python'))
# 0 1 2
# 0 True 93877 S26476961
# 1 True 93878 ['S26489167', 'S26492524']
# 2 False 93879 S26476962
# 3 False 93880 ['S26489168', 'S26492527', 'S26492528']
编辑2:
如果您不希望依赖引号字符’,您可以尝试以下方法:
import ast
import re
with io.StringIO(text) as f:
for line in f:
parts = re.split(", (?=\[)", line.strip())
line = []
for part in parts:
if all(char in part for char in ('[]')):
line.append(ast.literal_eval(part))
else:
line += part.split(", ")
print(line)
您拆分位于左方括号前面的逗号,然后按如下方式检查结果:
>检查从拆分操作生成的列表的每个元素是否都有方括号.如果是,则将其转换为具有ast.literal_eval的列表对象,并将其添加到最终输出列表中.
>否则,在逗号上拆分并将随后的列表添加到最终输出列表中.
这应该与上述解决方案相同.
我希望这有帮助.