2012-04-23 6 views
1
wordsFreq = {} 
words = [] 
while True: 
    inputWord = raw_input() 
    if (inputWord != ""): 
     words.append(inputWord) 
    else: 
     break 
for word in words: 
    wordsFreq[word] = wordsFreq.get(word, 0) + 1 

for word,freq in wordsFreq.items(): 
    print word + " - " + str(freq) 

명백히 내 단어 []와 for 루프는 중복되지만 그 이상의 설명이 없으므로 아무에게도 왜 중복되는지 설명 할 수 있습니까?파이썬 단어 수

+0

전체를 읽으면 단어를 계산할 수 있습니다. D : http://docs.python.org/library/collections.html#collections.Counter – jamylak

+0

목적은 카운터를 사용하지 않는 것입니다. – JamieB

+0

아, 그럴 경우 좋습니다. 좋습니다. 'defaultdict'를 사용하는 것이 허용되지 않는 한. – jamylak

답변

7

당신은 단어의 목록을 구축하는 단계를 건너 뛰고 사용자가 단어를 입력하는대로 대신 직접 주파수 DICT를 만들 수 있습니다. 단어가 이미 추가되었는지 확인하지 않으려면 defaultdict을 사용했습니다. 당신이 defaultdict를 사용할 수없는 경우

from collections import defaultdict 

wordsFreq = defaultdict(int) 
while True: 
    word = raw_input() 
    if not word: 
     break 
    wordsFreq[word] += 1 

,이 같을 수 :

wordsFreq = {} 
while True: 
    word = raw_input() 
    if not word: 
     break 
    wordsFreq[word] = wordFreq.get(word, 0) + 1 
0

이 작업을 수행 할 수 있습니다

wordsFreq = {} 
while True: 
    inputWord = raw_input() 
    try: 
     wordsFreq[inputWord] = wordsFreq[inputWord] + 1 
    except KeyError: 
     wordsFreq[inputWord] = 1 
쉽게이 작업을 수행 할 collections.Counter을 사용할 수 있습니다
+3

이런 식으로하면, defaultdict 또는''dict.get()''의 기본값을 사용하는 것이 더 좋을 것입니다. –

2

: 빈 문자열이 false로 평가하는 것이

from collections import Counter 

words = [] 
input_word = True 
while input_word: 
    input_word = raw_input() 
    words.append(input_word) 

counted = Counter(words) 

for word, freq in counted.items(): 
    print word + " - " + str(freq) 

주, 그래서 오히려 빈 같을 때 파괴보다 문자열을 사용하면 문자열을 루프 조건으로 만 사용할 수 있습니다.

편집은 다음 defaultdict 모든 키 0의 가치가있는 경우를 가리 킵니다 보장

from collections import defaultdict 

words = defaultdict(int) 
input_word = True 
while input_word: 
    input_word = raw_input() 
    if input_word: 
     words[input_word] += 1 

for word, freq in words.items(): 
    print word + " - " + str(freq) 

: 당신이 학문적으로 Counter을 사용하지 않으려면, 그 다음 최선의 선택은 collections.defaultdict입니다 전에 사용 된 적이 없습니다. 이렇게하면 우리가 쉽게 계산할 수 있습니다.

여전히 단어 목록을 유지하려는 경우 추가로해야합니다. 예컨대 :

words = [] 
words_count = defaultdict(int) 
input_word = True 
while input_word: 
    input_word = raw_input() 
    if input_word: 
     words.append(input_word) 
     words_count[input_word] += 1 
2

나는 선생님이이

wordsFreq = {} 
while True: 
    inputWord = raw_input() 
    if (inputWord != ""): 
     wordsFreq[inputWord] = wordsFreq.get(inputWord, 0) + 1 
    else: 
     break 

for word,freq in wordsFreq.items(): 
    print word + " - " + str(freq) 
같은 루프를 쓸 수있는 말하려고 한 생각

임시 목록에 단어를 저장할 필요가 없습니다.