python - How to count everything in quotes as only one item -
i'm trying split following string:
a = "2147486448, 'node[082, 101-107]', 8"
right i'm using str(a).strip('[]').split(",")
, output [2147486448, 'node[082,' '101-107]', 8] isn't want, expecting was[2147486448, 'node[082, 101-107]', 8]
but can see in second item of list, contains ',', should second item 1 instead of split ','
i've read post [how count occurrences of separator in string excluding in quotes still have no idea of should in case. , feel free delete post if guys think it's duplicate
update:
thanks @cyphase code works, when tried read line line txt file , each line:
a = [] f = open(txt_file) row in f: a.append(ast.literal_eval(row))
a snippet of txt file :
423, 0, 0, 'default', 8, 8, 0, null, 1, 'sacimport', 2990, null, 286, 232, 0, 0, 1486, 576, -1, 98304, 'node581', 1, '476', 'batch', 4294901555, 6, 60, 1403219907, 1403219907, 1403219908, 1403223513, 0, '', '', '', '', 0 424, 0, 0, 'default', 16, 16, 0, null, 0, 'b35planar-2.com', 2828, null, 287, 130, 0, 0, 24691, 16508, 24691, 16384, 'node582', 1, '477', 'batch', 4294901554, 4, 3600, 1403219914, 1403219914, 1403219915, 1403220421, 0, '', '', '', '', 0 425, 0, 0, 'default', 2, 2, 0, null, 0, 'ec', 704, null, 288, 248, 0, 0, 1798, 702, 1798, 2147486448, 'node514', 1, '409', 'sandy-batch', 4294901553, 4, 390, 1403220027, 1403220027, 1403220027, 1403220117, 0, '', '', '', '', 0
it says valueerror: malformed string, every row represents string right?
ast
fail every line, lines not wrapped in quotes , have empty lines, have csv file should parsed csv module, can use quotechar="'"
to strip single quotes , need skipinitialspace=true
.
open("in.txt") f: r = csv.reader(f, quotechar="'", skipinitialspace=true) row in r: print(row)
output adding 2147486448, 'node[082, 101-107]', 8
last line:
['423', '0', '0', 'default', '8', '8', '0', 'null', '1', 'sacimport', '2990', 'null', '286', '232', '0', '0', '1486', '576', '-1', '98304', 'node581', '1', '476', 'batch', '4294901555', '6', '60', '1403219907', '1403219907', '1403219908', '1403223513', '0', '', '', '', '', '0'] [] ['424', '0', '0', 'default', '16', '16', '0', 'null', '0', 'b35planar-2.com', '2828', 'null', '287', '130', '0', '0', '24691', '16508', '24691', '16384', 'node582', '1', '477', 'batch', '4294901554', '4', '3600', '1403219914', '1403219914', '1403219915', '1403220421', '0', '', '', '', '', '0'] [] ['425', '0', '0', 'default', '2', '2', '0', 'null', '0', 'ec', '704', 'null', '288', '248', '0', '0', '1798', '702', '1798', '2147486448', 'node514', '1', '409', 'sandy-batch', '4294901553', '4', '390', '1403220027', '1403220027', '1403220027', '1403220117', '0', '', '', '', '', '0'] [] ['2147486448', 'node[082, 101-107]', '8']
if don't care having single quotes, use skipinitialspace=true
:
with open("in.txt") f: r = csv.reader(f, quotechar="'", skipinitialspace=true) row in r: print(row)
Comments
Post a Comment