2014-11-07 4 views
0

사전을 사용하고 각 단어가 여러 사용자 입력에 나타나는 횟수를 계산해야하는이 연습 문제로 고생하고 있습니다. 그것은 유행에서 일하고, 그러나 사용자 입력의 각 선에서 각 낱말을 분무하지 않는다. 따라서 '행복한 날'의 입력을 1 x 행복과 1 x 일로 계산하는 대신 1 x 행복한 날을주게됩니다. 나는 split()을 lower()와 함께 시도했지만 이것은 입력을리스트로 변환하고 그리스트를 사전에 쏟아 부었다.워드 빈도 카운터 파이썬

짐작할 수 있듯이, 저는 초보자이기 때문에 모든 도움을 주시면 감사하겠습니다!

occurrences = {} 
while True: 
    word = input('Enter line: ') 
    word = word.lower() #this is also where I have tried a split() 
    if word =='': 
     break 
occurrences[word]=occurrences.get(word,0)+1 
for word in (occurrences): 
    print(word, occurrences[word]) 

편집 응답

건배. 결국 최종 솔루션이되었습니다. 그들은 사건에 대해 걱정하지 않고 최종 결과를 정렬하기를 원했습니다().

occurrences = {} 
while True: 
    words = input('Enter line: ') 
    if words =='': 
     break 
    for word in words.split(): 
     occurrences[word]=occurrences.get(word,0)+1 
for word in sorted(occurrences): 
    print(word, occurrences[word]) 
+0

당신이 우리에게 코드의 일부 샘플 입력과 출력을 줄 수 있습니까? – wnnmaw

+0

입력 행을 split() 한 후에는 새롭게 구성된 목록을 반복하여 각 개별 단어를 사전 카운터에 추가해야합니다. – hexparrot

+0

또한 게시하거나 원본 코드의 일부분 일지 모르지만 코드가 while 루프에서 벗어날 기회가없는 것으로 들여다 보면 들여 쓰기가 잘못되었음을 알 수 있습니다 (여기에서 게시물에 있음) – hexparrot

답변

0

당신이 가진 것은이 줄은 실행되지 않습니다

occurrences = {} 
while True: 
    words = input('Enter line: ') 
    words = words.lower() #this is also where I have tried a split() 
    if words =='': 
     break 
    for word in words.split(): 
     occurrences[word]=occurrences.get(word,0)+1 
    for word in (occurrences): 
     print(word, occurrences[word]) 
0

DICT에 추가 할 때 그냥 단어를 반복 할 원하는 거의가 : 발생 [단어] = occurrences.get (단어, 0) +1

if가 입력되면 중단으로 이동하고 절대로 실행하지 않기 때문입니다. 들여 쓰기를하지 않으려면 그것의 외부에 있어야합니다.

일반적으로 게시 된 코드의 들여 쓰기가 엉망입니다. 실제 코드에서는 그렇게 들리지 않습니다.

0

줄 단위 통계를 원하거나 전체 통계를 원하십니까? 난 당신이 라인으로 라인을 원하는 같은데요,하지만 당신은 또한 다음과 같은 코드 몇 줄의 주석으로 전체 통계를 쉽게 얻을 수 있습니다 :

# occurrences = dict() # create a dictionary here if yuo want to have incremental overall stats 
while True: 
    words = input('Enter line: ') 
    if words =='': 
     break 
    word_list = words.lower().split() 
    print word_list 
    occurrences = dict() # create a dict here if you want line by line stats 
    for word in word_list: 
     occurrences[word] = occurrences.get(word,0)+1 

    ## use the lines bellow if you want line by line stats 
    for k,v in occurrences.items(): 
     print k, " X ", v 

## use the lines bellow if you want overall stats 
# for k,v in occurrences.items(): 
    # print k, " X ", v