2017-03-19 5 views
-1

マップリダクションの一部として逆さまの検索を実装しようとしていますが、その最初の部分は完成(マッパー)できました。最初の部分の出力は 以下のようなもの(見出しは参考のために、これらはマッパーの実際の出力に含まれていないされている)Pythonの反転検索

word  frequency  document 
------------------------------ 
tire  1   car 
headlight 1   shop 
tire  1   car 
gas   1   gasstation 
beer  1   gasstation 
headlight 1   car 
tire  1   shop 

に見える私は解決策以下に取得しようとしている:

単語が発見されましたそのファイル内に、その頻度とともに表示されます。 (例えば、車のファイルにタイヤが2回見つかります)

これまでは、単語を含むファイルを取得するために辞書を使用しようとしましたが、カウントを取得するためにリンクできませんでした。メートル取得:期待

{'car':[tire,tire,headlight],'shop':[headlight],'gasstation':[gas,beer]} 

tire   {'car':2,'shop':1} 
headlight  {'car':1, 'shop':1} 
+1

"expected"は* desired *出力のプレースホルダーではありません。なぜその成果を期待したのですか?あなたがそれを作り出すと思われるコードはどこですか? [mcve]を与える。 – jonrsharpe

+0

Counterクラスを見てください –

答えて

0

は、あなたが望むものはreduceにあなたがグループにあなたのリスト内の要素を持っている辞書です。

mapped_data = [ 
    { 'word': 'tire', 'frequency': 1, 'document': 'car' }, 
    { 'word': 'headlight', 'frequency': 1, 'document': 'shop' } 
] 

その後、あなたのような何かができる:

{ 
    'tire': { 
     'car': 2, 
     'shop': 1 
    }, 
    'headlight': { 
     ... 
    }, 
    ... 
} 

def reducer(accumulated, line): 
    # We've never seen this word before, create the dict to store the documents 
    if line['word'] not in accumulated: 
     accumulated[line['word']] = {} 

    # We've never seen this word in this document before, initialize the counter. 
    if line['document'] not in accumulated[line['word']]: 
     accumulated[line['word']][line['document']] = 0 

    # Increment th counter 
    accumulated[line['word']][line['document']] += line['frequency'] 

    return accumulated_data 

reduce(reducer, mapped_data, {}) 

これは期待どおりの結果を生成するあなたのマッピングの出力は、このようなdictsのリストであると仮定すると、