Python 将逗号分隔的数据转换为不带CSV模块的列表
我正在上数据库课,对python有点生疏。我的作业如下-- 转换此文本:Python 将逗号分隔的数据转换为不带CSV模块的列表,python,list,csv,split,comma,Python,List,Csv,Split,Comma,我正在上数据库课,对python有点生疏。我的作业如下-- 转换此文本: "col 1", "col 2", "col 3" 1, 'abc', 2 3, "de,fg", 4 5, , 6 为此: [ "col 1", "col 2", "col 3" ] [ 1, 'abc', 2 ] [ 3, "de,fg", 4] [ 5, None, 6] 到目前为止,我所拥有的只是这个(很悲伤): 我现在需要python程序做的就是打印上面的内容。问题是我们不允许使用CSV模块,s.split(
"col 1", "col 2", "col 3"
1, 'abc', 2
3, "de,fg", 4
5, , 6
为此:
[ "col 1", "col 2", "col 3" ]
[ 1, 'abc', 2 ]
[ 3, "de,fg", 4]
[ 5, None, 6]
到目前为止,我所拥有的只是这个(很悲伤):
我现在需要python程序做的就是打印上面的内容。问题是我们不允许使用CSV模块,s.split(',')
不起作用,因为一个字符串包含逗号
非常感谢您的帮助。我正在拔头发,因为我找不到任何不包含CSV模块的提示
谢谢
def smart_split(s,token=","):
in_quotes = False
current_idx = 0
for i,c in enumerate(s):
if c in "\"'":
in_quotes = not in_quotes
elif c == token and not in_quotes:
yield s[current_idx:i].strip()
current_idx = i+1
yield s[current_idx:].strip()
print list(smart_split('3, "de,fg", 4'))
print map(smart_split,open("some_File.txt"))
也许能帮你开始。。。可能有更好的方法,但我认为这基本上对您有效…这对您的特定输入有效
data = open('/file', 'r').read()
dataS = [i for i in data.split('\n') if i]
for i in dataS:
print(i.split(', '))
输出:
['"col 1"', '"col 2"', '"col 3"']
['1', "'abc'", '2']
['3', '"de,fg"', '4']
['5', '', '6']
['"col 1"', '"col 2"', '"col 3"']
['1', "'abc'", '2']
['3', '"de,fg"', '4']
['5', '', '6']
通过正则表达式
import re
data = open('/home/avinash/Desktop/ri', 'r').read()
dataS = [i for i in data.split('\n') if i]
for i in dataS:
print(re.split(r'\s*,\s*(?=(?:"[^"]*"|\'[^\']*\'|[^\'"])*$)', i))
输出:
['"col 1"', '"col 2"', '"col 3"']
['1', "'abc'", '2']
['3', '"de,fg"', '4']
['5', '', '6']
['"col 1"', '"col 2"', '"col 3"']
['1', "'abc'", '2']
['3', '"de,fg"', '4']
['5', '', '6']
如果您想通过使用简单的运算符和条件来实现此问题的最基本方法,请参见:
data = open("DatabaseTest.txt", 'r').read()
csv = ""
i = 0
l = len(data)
for char in data:
i += 1
if csv == "":
csv += "["
if char == "\n":
csv += "]"
csv += char
csv += "["
else:
csv += char
if char == ",":
if data[i+1] == "," or data[i] == ",":
csv += " None"
if i == l:
csv += "]"
print csv
请注意,这并不是解决您问题的最佳方法,但这肯定会对您的任务起作用
还有普洛夫
它只会使字符串输出不是列表。提示:使用正则表达式。或者,使用一个简单的状态机,解析字符并跟踪打开/关闭转义引号以查找拆分索引。拆分并迭代数组,跟踪是否传递了打开的
“
,而没有看到关闭的”
(请记住,\“
是一个转义的”
,不计算在内)。如果你在引号内,那么继续将标记与,
粘在一起,直到你到达结束“
。我感谢所有的回答,但没有一个是完全正确的。根据我对赋值的理解,输出实际上应该是一个打印的列表,而不仅仅是一个格式类似列表的字符串。s.split(','))确实有效,但我可以看到他说它不适用于所有情况。我认为@Aruistante关于解析的评论是正确的,但我从未学会如何使用它。我现在正在尝试自学,如果我弄明白了,我会更新!