2016-12-03 14 views
0

1つの辞書から一意の第1タプル値に基づいて新しい個別辞書を作成し、対応するキーと値をマップできますか?Python:新しい辞書を作成するタプルのインデックス化

の作業の説明:

this = {'dog': 3, 'animal': 3} animal = {'this': 3, 'animal': 1} dog = {'this': 2, 'that': 1} that = {'animal': 1}

:このことから

Counter({('this', 'dog'): 3, ('this', 'animal'): 3, ('animal', 'this'): 3, ('dog', 'this'): 2, ('animal', 'animal'): 1, ('dog', 'that'): 1, ('that', 'animal'): 1})

が、これらの個々のdictsを作成することが可能である:

import re 
from collections import Counter 

TestString = 'this dog, this dog. this, animal this animal animal this animal this dog that animal' 

def get_dict(string): 

    # Create list of individual words without punctuation 
    x = re.findall(r"[\w']+", string) 

    # Get sum of individual two-word shingles from list 
    x = (Counter(zip(x,x[1:]))) 
    print x 

get_dict(TestString) 

には、以下の辞書を返します。新しいdict名はタプルの一意の第1要素であり、キーと値はそれに応じてマップされますか?

+0

それは可能ですが、ほとんどの場合それを望んでいません...辞書ウィットh個の 'this' /' animal'などのユニークキー...その値は辞書ですか? –

+0

これは、下流分析に必要なデータを構造化するための特別なアプローチです。 – RDJ

+0

どのような単語が構文的に有効な変数名またはシャドービルトインでないか、キーワードと同じである場合はどうなりますか? :p –

答えて

1

キー最初の言葉であり、その値が2番目の単語と周波数の辞書は、例えば、単一の辞書を作成します。

from collections import defaultdict 
import re 

text = 'this dog, this dog. this, animal this animal animal this animal this dog that animal' 
words = re.findall('\w+', TestString) 
counts = defaultdict(lambda: defaultdict(int)) 
for word1, word2 in zip(words, words[1:]): 
    counts[word1][word2] += 1 

これはあなたのようにcountsあげる:

defaultdict(<function <lambda> at 0x7f0ca8565378>, 
      {'animal': defaultdict(<class 'int'>, {'animal': 1, 'this': 3}), 
      'dog': defaultdict(<class 'int'>, {'that': 1, 'this': 2}), 
      'that': defaultdict(<class 'int'>, {'animal': 1}), 
      'this': defaultdict(<class 'int'>, {'animal': 3, 'dog': 3})}) 

counts['this']['dog']のようなものが返されます3 ...等

関連する問題