9

私は次の形式のPython文字列を持っています:

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

次のような辞書に変換する方法はありますか

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

ここで、各エントリは文字列から取得した (キー、値) のペアです。リストする文字列を分割してみました

str.split()  

次に、手動で を削除し:、各タグ名を確認し、辞書に追加します。この方法の欠点は次のとおりです。この方法は厄介です。:ペアごとに手動で削除する必要があり、文字列に複数の単語「値」がある場合 (たとえば、blah blahfor description)、各単語はリスト内の個別のエントリになります。望ましくない。(Python 2.7 を使用して) 辞書を取得する Pythonic の方法はありますか?

4

3 に答える 3

35
>>> 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
于 2012-04-30T09:07:56.457 に答える
3

なしre

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'}
于 2012-04-30T09:07:22.740 に答える
0

辞書を元の順序で表示する 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)

出力

[('name', 'srek'), ('age', '24'), ('description', 'blah blah'), ('cat', 'dog'), ('stack', 'overflow')]

于 2013-01-25T03:32:48.697 に答える