2017-03-19 10 views
-1

지도 반전의 일부로 역변환을 구현하려고합니다. 첫 번째 부분은 완료 할 수있었습니다 (매퍼).파이썬에서 역순으로 검색

단어가 발견 : 첫 번째 부분의 출력은 내가 솔루션 아래에 도착하기 위해 노력하고있어

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

을 (표제는 참조 용으로, 이러한 매퍼의 실제 출력에 있지된다) 아래 같이 보입니다 이 파일에는 빈도가 표시됩니다. (예를 들어 자동차 파일에서 타이어가 두 번 발견됨)

지금까지는 사전을 사용하여 단어가있는 파일을 얻으려고 시도했지만 그 수를 얻기 위해 연결할 수 없습니다. m 점점 : 예상

{'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

카운터 클래스 살펴보기 –

답변

0

당신이 원하는 무엇 reduce에 당신이 그룹에 목록의 요소를 가지고 DICT이다.

{ 
    '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, {}) 

이 :

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

그런 다음 당신이 뭔가를 할 수 있습니다 : 당신의 매핑의 출력을 가정

이 같은 dicts의 목록입니다