Sascuash
Sascuash

Reputation: 3831

convert unicode string into array. Django-Python

I receive via POST an unicode string like this:

u'[<Word: colors>, <Word: red>, <Word: blue>, <Word: yellow>, <Word: green>, <Word: orange>, <Word: purple>, <Word: brown>, <Word: white>, <Word: black>, <Word: grey>]'

I want it to be an array or a dictionary so I can work with it.

How can I do this?

Thanks.

Upvotes: 0

Views: 263

Answers (2)

Denis Nikanorov
Denis Nikanorov

Reputation: 832

I think there must be a way to change the format of your data (because as I see you try to output list of python objects to form field what is not good idea).

Without more information about your code I can offer this:

output to form field 'colors,red,blue,yellow...'

then after post: list_of_values = input.split(',') (where input is recieved string from post)

Also you can use this code based what output you need

print map(lambda val: val.strip(' <>'), s.strip('[]').split(','))
print map(lambda val: val.strip(' <>').split(':')[1].strip(), s.strip('[]').split(','))

Also you can serialize or pickle data.

Upvotes: 0

user3159253
user3159253

Reputation: 17455

You should use a module for parsing a structured text, for example, pyparsing. Basically the grammar should look like this:

import pyparsing as pp

s = u'[<Word: colors>, <Word: red>, <Word: blue>, <Word: yellow>, <Word: green>, <Word: orange>, <Word: purple>, <Word: brown>, <Word: white>, <Word: black>, <Word: grey>]'

term = pp.Literal('<') + pp.Literal('Word') + pp.Literal(':') + pp.Word(pp.alphas) + pp.Literal('>')
expr = pp.Literal('[') + term + pp.ZeroOrMore( pp.Literal(',') + term ) + pp.Literal(']')

r = expr.parseString(s)

and then retrieve parse results from r. Check examples on the project site. Probably you'll need to set up specific parser callbacks on the items you wish to extract using setParseAction():

import pyparsing as pp

s = u'[<Word: colors>, <Word: red>, <Word: blue>, <Word: yellow>, <Word: green>, <Word: orange>, <Word: purple>, <Word: brown>, <Word: white>, <Word: black>, <Word: grey>]'

colors = []

term = pp.Literal('<') + pp.Literal('Word') + pp.Literal(':') + pp.Word(pp.alphas).setParseAction(lambda s: colors.append(s[0])) + pp.Literal('>')
expr = pp.Literal('[') + term + pp.ZeroOrMore( pp.Literal(',') + term ) + pp.Literal(']')

r = expr.parseString(s)

now colors contains the list of colors and so on...

Upvotes: 2

Related Questions