【问题标题】:How to split and extract each tagname from the list of tags which is in the json data?如何从 json 数据中的标签列表中拆分和提取每个标签名?
【发布时间】:2013-11-07 04:09:24
【问题描述】:
      "tags" : "['x', 'y', 'z']"

我想提取每个元素并将每个元素添加到标签表中,例如

       tag1 = x
       tag2 = y 
       tag3 = z 

我需要将标签表中的每个标签存储在事件的不同行中。

     table: Event
       id, title, ...

     table: Tag
       Tagid, eventid, tagname

每个事件的标签可能不同。

【问题讨论】:

    标签: python-2.7 django-models


    【解决方案1】:

    或者没有评估:

    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 是邪恶的,因为它会受到代码注入的影响,因此可能无法预测。但只要你相信输入,应该没问题。使用ast.literal_eval 比 eval 好得多,因为它只计算基本类型,因此您不必担心代码注入。

    【讨论】:

      【解决方案2】:
      >>> t = {"tags" : "['x', 'y', 'z']"}
      >>> import ast
      >>> ast.literal_eval(t['tags'])
      ['x', 'y', 'z']
      

      现在是list

      【讨论】:

      【解决方案3】:

      根据 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()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-07
        • 2022-08-17
        • 2018-11-10
        • 1970-01-01
        相关资源
        最近更新 更多