[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.
>>> 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.다시하지 않고 :
다시하지 않고 :
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.사전을 사전에 표시하는 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', '설명', 'ㅋㅋ', '고양이', '개' )]
from https://stackoverflow.com/questions/10380992/get-python-dictionary-from-string-containing-key-value-pairs by cc-by-sa and MIT license
'PYTHON' 카테고리의 다른 글
[PYTHON] Atom에서 Python 실행하기 (0) | 2018.10.29 |
---|---|
[PYTHON] 파이썬에 내장 된 제품 ()이 있습니까? [복제] (0) | 2018.10.29 |
[PYTHON] 파이썬 : 다중 처리 풀을 사용하는 동안 큐가있는 단일 파일에 쓰기 (0) | 2018.10.29 |
[PYTHON] OpenCV 도트 타겟 탐지가 모든 타겟을 찾지 못하고, 발견 된 원이 상쇄됩니다. (0) | 2018.10.29 |
[PYTHON] 파이썬에서 한 파일의 무작위 라인을 읽으려면 어떻게해야합니까? (0) | 2018.10.28 |