0
      "tags" : "['x', 'y', 'z']"

I want to extract each element and add each element to a tag table like

       tag1 = x
       tag2 = y 
       tag3 = z 

I need to store each tag in tags table in different rows for a event.

     table: Event
       id, title, ...

     table: Tag
       Tagid, eventid, tagname

Tags can vary for each event.

4

3 回答 3

0
>>> t = {"tags" : "['x', 'y', 'z']"}
>>> import ast
>>> ast.literal_eval(t['tags'])
['x', 'y', 'z']

现在它是一个列表

于 2013-11-07T04:14:36.433 回答
0

或者没有评估:

t = {"tags" : "['x', 'y', 'z']"}
tags = [el.replace("'","").strip() for el in t['tags'][1:-1].split(',')]

# Basic string splitting:
tags = t['tags'].split(',')

# To replace a character in a string, like "z"
"a123".replace("a", "b") => "b123

# To strip whitespace:
"  Wow  ".strip() => "Wow"

# Then, a list comprehension to loop through elements of an array and put them in new array:
x = [1, 2, 3]
y = [i+1 for i in x]  =>  [2, 3, 4]

# All together, this becomes
tags = [el.replace("'","").strip() for el in t['tags'][1:-1].split(',')]

有人说 eval 是邪恶的,因为它受到代码注入的影响,因此可能无法预测。但只要你相信输入,应该没问题。usingast.literal_eval比 eval 好得多,因为它只计算基本类型,因此您不必担心代码注入。

于 2013-11-07T04:23:31.740 回答
0

根据 Ignacio Vazquez-Abrams 给出的答案,我可以将其更改为如下列表:

     tags = ast.literal_eval(tags)  #converted to the list

     ##Stored the tags with event_id in the tags table. 
     eventobj = Event.objects.get(pk=1)
     for i in range(len(tags)):
        tagsobj = Tags.objects.create(name = tags[i], event_id = eventobj.pk)
     tagsobj.save()
于 2013-11-07T05:09:30.793 回答