복붙노트

[PYTHON] 키 값 쌍을 포함하는 문자열에서 파이썬 사전 가져 오기

PYTHON

키 값 쌍을 포함하는 문자열에서 파이썬 사전 가져 오기

나는 형식으로 파이썬 문자열을 가지고 :

str = "name: srek age :24 description: blah blah"

거기에 보이는 사전으로 변환 할 수있는 방법이 있습니까?

{'name': 'srek', 'age': '24', 'description': 'blah blah'}  

여기서 각 항목은 문자열에서 가져온 (키, 값) 쌍입니다. 목록에 문자열을 분할하려고했습니다.

str.split()  

수동으로 제거 : 태그 이름 확인, 사전 추가. 이 방법의 단점은 다음과 같습니다.이 방법은 지저분합니다. 수동으로 제거해야합니다. 각 쌍에 대해 문자열에 'value'라는 단어가 여러 개있는 경우 (예 : 설명을 위해 blah blah) 각 단어는 바람직한 목록이 아닙니다. 파이썬 2.7을 사용하여 사전을 가져 오는 파이썬적인 방법이 있습니까?

해결법

  1. ==============================

    1.

    >>> r = "name: srek age :24 description: blah blah"
    >>> import re
    >>> regex = re.compile(r"\b(\w+)\s*:\s*([^:]*)(?=\s+\w+\s*:|$)")
    >>> d = dict(regex.findall(r))
    >>> d
    {'age': '24', 'name': 'srek', 'description': 'blah blah'}
    

    설명:

    \b           # Start at a word boundary
    (\w+)        # Match and capture a single word (1+ alnum characters)
    \s*:\s*      # Match a colon, optionally surrounded by whitespace
    ([^:]*)      # Match any number of non-colon characters
    (?=          # Make sure that we stop when the following can be matched:
     \s+\w+\s*:  #  the next dictionary key
    |            # or
     $           #  the end of the string
    )            # End of lookahead
    
  2. ==============================

    2.다시하지 않고 :

    다시하지 않고 :

    r = "name: srek age :24 description: blah blah cat: dog stack:overflow"
    lis=r.split(':')
    dic={}
    try :
     for i,x in enumerate(reversed(lis)):
        i+=1
        slast=lis[-(i+1)]
        slast=slast.split()
        dic[slast[-1]]=x
    
        lis[-(i+1)]=" ".join(slast[:-1])
    except IndexError:pass    
    print(dic)
    
    {'age': '24', 'description': 'blah blah', 'stack': 'overflow', 'name': 'srek', 'cat': 'dog'}
    
  3. ==============================

    3.사전을 사전에 표시하는 Aswini 프로그램의 다른 변형

    사전을 사전에 표시하는 Aswini 프로그램의 다른 변형

    import os
    import shutil
    mystr = "name: srek age :24 description: blah blah cat: dog stack:overflow"
    mlist = mystr.split(':')
    dict = {}
    list1 = []
    list2 = []
    try:
     for i,x in enumerate(reversed(mlist)):
        i = i + 1
        slast = mlist[-(i+1)]
        cut = slast.split()
        cut2 = cut[-1]
        list1.insert(i,cut2)
        list2.insert(i,x)
        dict.update({cut2:x})
        mlist[-(i+1)] = " ".join(cut[0:-1])
    except:
     pass   
    
    rlist1 = list1[::-1]
    rlist2= list2[::-1]
    
    print zip(rlist1, rlist2)
    

    산출

    ( '이름', 'srek'), '나이', '24', '설명', 'ㅋㅋ', '고양이', '개' )]

  4. from https://stackoverflow.com/questions/10380992/get-python-dictionary-from-string-containing-key-value-pairs by cc-by-sa and MIT license