Created
September 16, 2014 11:12
-
-
Save npalko/2232fb50a8487740722b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Parser(object): | |
def __call__(self, s): | |
self.remains_ = s | |
self.state_ = 'in_key' | |
self.key_ = [] | |
self.value_ = [] | |
disbatch = { | |
'in_key': self.in_key, | |
'in_value': self.in_value, | |
'in_quoted_value': self.in_quoted_value, | |
} | |
while len(self.remains_) > 0: | |
disbatch[self.state_]() | |
return dict(zip(self.key_,self.value_)) | |
def in_key(self): | |
key, ignore, self.remains_ = self.remains_.partition(':') | |
print '{self.state_} [{key}] [{self.remains_}]'.format(**locals()) | |
self.key_.append(key) | |
if self.remains_.startswith("'"): | |
self.state_ = 'in_quoted_value' | |
else: | |
self.state_ = 'in_value' | |
def in_value(self): | |
value, ignore, self.remains_ = self.remains_.partition(' ') | |
print '{self.state_} [{value}] [{self.remains_}]'.format(**locals()) | |
self.value_.append(value) | |
self.state_ = 'in_key' | |
def in_quoted_value(self): | |
value, ignore, self.remains_ = self.remains_[1:].partition("'") | |
print '{self.state_} [{value}] [{self.remains_}]'.format(**locals()) | |
self.value_.append(value) | |
self.state_ = 'in_key' | |
def test(): | |
print dict(parse('a:b c:d e:ff')) == {'a':'b', 'c':'d', 'e':'ff'} | |
""" | |
# read to next ':' | |
# read to next ' ' | |
# read to next ''' | |
- between last index and this current one, i need to | |
-- yield a key | |
-- yield a value | |
-- reconize i'm in a quoted field, and read to the next ' | |
-- if i hit a quote, i'm either at the end of a quoted field, | |
state = 'in_key' | |
key = '' | |
value = '' | |
for c in line: | |
if state == 'in_key' | |
if c != ':': | |
key += c | |
else: | |
yield key | |
key = '' | |
""" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment