2017-11-11 1 views
1

단어 (문자열) 목록을 취하고 각각의 특정 단어가 몇 번이나 나오는지 계산하고 단어가 나타나는 횟수를 사전으로 반환하는 함수를 작성하려고합니다. 목록을 목록의 총 단어 수 (용어 빈도 벡터)로 나눈 값입니다.용어 빈도 값의 사전 만들기

def makeTermFrequencyVector(wordList): 
''' 
makeTermFrequencyVector Takes a list of words as parameter and returns a dictionary representing the term frequency 
vector of the word list, where words are keys and values are the frequency of occurrence of 
each word in the document. 
''' 
tfDict = {} 
for word in wordList: 
    for i in range(len(wordList)): 
     state = 0 
     if wordList[i] == word: 
      state += 1 
    tfv = state/(len(wordList)) 
    tfDict[word] = tfv 
return tfDict 

내가 입력 된 경우

makeTermFrequencyVector(['cat', 'dog']): 

출력이어야 각 단어 2.

그러나 총 길이의리스트에 한번 표시

{'cat': 0.5, 'dog': 0.5} 

때문에, 이것을 코드는 올바른 tf 값을 가진 입력 목록의 마지막 단어 만 포함한 사전을 반환하고 다른 모든 단어는 ' 값이 0입니다. 따라서 위의 목록을 현재 코드에 입력하려고하면 다음을 반환합니다.

{'dog': 0.5, 'cat': 0.0} 

올바르지 않습니다.

이 문제를 해결하여 마지막 단어뿐만 아니라 목록의 각 단어에 대한 값을 반복 할 수 있습니까? 가능한 고정 코드를 현재 코드에 가깝게 유지하고 싶습니다.

+0

코드의 첫 번째 줄 뒤에 모든 코드가 들여 쓰기되어야합니다 (함수 안에 있기 때문에). –

답변

0

단어를 중첩 통과하는 대신 별도의 패스를 만드는 것이 더 간단합니다. 첫 번째 단계에서 우리는 단어 수를 취합니다. 두 번째 패스에서, 우리는 주파수를 가진 단어 수를 대체 :

def makeTermFrequencyVector(wordList): 
    ''' 
    Takes a list of words and returns a dictionary representing 
    the term frequency vector of the word list, where words are 
    keys and values are the frequency of occurrence. 
    ''' 

    tfDict = dict() 

    for word in wordList: 
     tfDict[word] = tfDict.get(word, 0) + 1 

    word_count = len(wordList) 

    for word in tfDict: 
     tfDict[word] /= word_count 

    return tfDict 

print(makeTermFrequencyVector(['cat', 'dog'])) 

word_list = [ \ 
    'Takes', 'a', 'list', 'of', 'words', 'as', 'its', 'sole', 'parameter', \ 
    'and', 'returns', 'a', 'dictionary', 'representing', 'the', 'term', \ 
    'frequency', 'vector', 'of', 'the', 'word', 'list,', 'where', 'words', \ 
    'are', 'keys', 'and', 'values', 'are', 'the', 'frequency', 'of', \ 
    'occurrence', 'of', 'each', 'word', 'in', 'the', 'source', 'document', \ 
] 

print(makeTermFrequencyVector(word_list)) 

OUTPUT 2 패스 접근 방식의

> python3 test.py 
{'cat': 0.5, 'dog': 0.5} 
{'Takes': 0.025, 'a': 0.05, 'list': 0.025, 'of': 0.1, 'words': 0.05, 'as': 0.025, 'its': 0.025, 'sole': 0.025, 'parameter': 0.025, 'and': 0.05, 'returns': 0.025, 'dictionary': 0.025, 'representing': 0.025, 'the': 0.1, 'term': 0.025, 'frequency': 0.05, 'vector': 0.025, 'word': 0.05, 'list,': 0.025, 'where': 0.025, 'are': 0.05, 'keys': 0.025, 'values': 0.025, 'occurrence': 0.025, 'each': 0.025, 'in': 0.025, 'source': 0.025, 'document': 0.025} 
> 
0

cdlane의 사용은 루프를 중첩하여 대 길을 가야하는 것입니다. 그 이유는 각 패스가 O (n) 시간이 걸릴 것이기 때문입니다. 여기서 n은리스트의 길이입니다. 두 번 통과하면 O (n) + O (n) = O (2n) 시간이되지만 상수는 O (n) 점근 시간을 만들기 위해 떨어집니다.

state이 내부 루프에 배치되어 있기 때문에 코드가 작동하지 않는 이유 중 일부가 있습니다. 따라서 루프가 반복 될 때마다 상태는 매번 단순히 증가되는 것이 아니라 0으로 재설정됩니다. state = 0 라인을 가져 와서 루프 내부에서 튀어 나오면 논리가 작동해야한다고 생각합니다.