2016-04-19 18 views
-2

基本的に、私は辞書から数字と文字を分けて、それらの間にスペースを入れることができるフィルタを書こうとしています。したがって、例えば12346 S12346 Qです。文字と数字の間のスペース

def check_if_works(): 
    dict_info = {} 
    dict_info['1234'] = "test" 
    dict_info['12456s'] = "test" 
    dict_info['12456q'] = "test" 
    dict_info['12456b'] = "test" 
    dict_info['123456'] = "test" 
    dict_info['asdftes'] = "test" 
    dict_info['asdftess'] = "test" 
    dict_info['asdftessd'] = "test" 
    arr = [] 
    for key,value in dict_info.iteritems(): 
     if key.isalpha() or key.isdigit(): 
      pass 
     #print key 
     else: 
      print key 

答えて

0

ディクショナリのリストは必要ありません。新しいディクテーションを直接入力してダンプする必要があります。 は決して例外をスローしないので、try/exceptの必要はありません。文字と数字だけを含むことをテストするためにチェックを組み合わせてください(isalnum())。文字(isalpha())または数字(isdigit())のみです。

また、反復ステップごとに元の辞書に1回だけ書き込むのではなく、最後に1回だけ結果ディクショナリをダンプします。

new_dict = {} 

for key,value in dict_info.iteritems(): 
    check = key.isalnum() and not (key.isalpha() or key.isdigit()) 

    new_dict[insert_spaces(key)] = value 
    print (key, ":", value) 

with open('output.json', 'wb') as outfile: 
    json.dump(new_dict, outfile, indent=4) 

あなたは数字+文字または文字+数字の間にスペースを挿入する必要がある機能insert_spacesは、次のようになります。

import re 
def insert_spaces(key): 
    return re.sub(r'(\D)(\d)', r"\1 \2", re.sub(r'(\d)(\D)', r"\1 \2", key)) 

はまた、あなたが(辞書の理解とそのコード全体を置き換えることができますPython 2.7以降):

with open('output.json', 'wb') as outfile: 
    json.dump({ insert_spaces(key): dict_info[key] for key in dict_info if key.isalnum() and not (key.isalpha() or key.isdigit()) }, outfile, indent=4) 

チェックを抜かないと

check_key = lambda key: key.isalnum() and not (key.isalpha() or key.isdigit()) 
with open('output.json', 'wb') as outfile: 
    json.dump({ insert_spaces(k): dict_info[k] for k in dict_info if check_key(k) }, 
       outfile, indent=4) 
+0

ちょっと、私は文字と数字を分割して、両方にスペースを持たせることができます。 – Benji

+0

@Benjiこれに使用できる機能が追加されました。 're'モジュールをインポートする必要があることに注意してください。 –

+0

甘い。私は最後の質問が1つあります。だから根本的に、私はCS 10、CS 70などの鍵を持っているとしましょう。最初の数文字が同じなら、私がやりたいことは合格です。それらが同じでない場合は、リストに追加してください。 2単語を比較するのと同じように。 – Benji

関連する問題