2013-07-14 7 views
1

텍스트 파일에서 가장 많이 나타나는 단어를보고하도록 프로그램을 설정하려고합니다. 예를 들어, "Hello like I like pie"라고 입력하면 프로그램이 "가장 많이 발생한 것"을 인쇄해야합니다. KeyError를 : 옵션 3을 실행했을 때이 오류가 'H'Python : 가장 많이 나타나는 단어 찾기?

#Prompt the user to enter a block of text. 
done = False 
textInput = "" 
while(done == False): 
    nextInput= input() 
    if nextInput== "EOF": 
     break 
    else: 
     textInput += nextInput 

#Prompt the user to select an option from the Text Analyzer Menu. 
print("Welcome to the Text Analyzer Menu! Select an option by typing a number" 
    "\n1. shortest word" 
    "\n2. longest word" 
    "\n3. most common word" 
    "\n4. left-column secret message!" 
    "\n5. fifth-words secret message!" 
    "\n6. word count" 
    "\n7. quit") 

#Set option to 0. 
option = 0 

#Use the 'while' to keep looping until the user types in Option 7. 
while option !=7: 
    option = int(input()) 

#The error occurs in this specific section of the code. 
#If the user selects Option 3, 
    elif option == 3: 
     word_counter = {} 
     for word in textInput: 
      if word in textInput: 
       word_counter[word] += 1 
      else: 
       word_counter[word] = 1 

     print("The word that showed up the most was: ", word) 

답변

2

당신이 수행 할 수 있습니다 생각 :

for word in textInput.split(): 
    ... 

는 현재, 당신은 단지 textInput의 모든 문자를 반복한다. 따라서 모든 단어를 반복하려면 먼저 문자열을 단어 배열로 분할해야합니다. 기본적으로 .split()은 공백으로 나뉘지만 범위를 split()으로 전달하면 변경할 수 있습니다.


또한 단어가 사전에없고 원래 문자열에 있는지 확인해야합니다. 그래서 시도 :

if word in word_counter: 
    ... 

을 그리고, 가장 높은 발생을 가진 항목을 찾을 수 :

highest_word = "" 
highest_value = 0 

for k,v in word_counter.items(): 
    if v > highest_value: 
    highest_value = v 
    highest_word = k 

그리고, 단지 highest_wordhighest_value의 값을 출력.


동점을 추적하려면 가장 높은 단어 목록을 유지하십시오. 더 높은 발생을 발견하면 목록을 지우고 재건을 계속하십시오. 지금까지 전체 프로그램이 있습니다 :

textInput = "He likes eating because he likes eating" 
word_counter = {} 
for word in textInput.split(): 
    if word in word_counter: 
    word_counter[word] += 1 
    else: 
    word_counter[word] = 1 


highest_words = [] 
highest_value = 0 

for k,v in word_counter.items(): 
    # if we find a new value, create a new list, 
    # add the entry and update the highest value 
    if v > highest_value: 
    highest_words = [] 
    highest_words.append(k) 
    highest_value = v 
    # else if the value is the same, add it 
    elif v == highest_value: 
    highest_words.append(k) 

# print out the highest words 
for word in highest_words: 
    print word 
+0

나는 여전히 .split() – user2581724

+0

난 그냥 실현을 통합 한 후 키 오류, 내 업데이트 된 대답을 살펴 있습니다. – Th3Cuber

+0

자, 이제 프로그램은 입력 단계에서 입력 한 마지막 단어 만 인쇄합니다. 내가 "그 사람이 너무 닮은 것 같아"라고 말하면, 단어의 뜻이 나타나고 "좋아"하지 않습니다. 무엇이 잘못 될 수 있습니까? – user2581724

-1

저는 파이썬에 열중하지 않습니다 만, 마지막 인쇄문에 % s이 없어야합니까?

예 : 인쇄 ("나타났다 단어 가장이었다 % s '에, 워드)

1

원래의 대답은 확실히 정확하지만 당신은 당신이 표시되지 않습니다 것을 명심해야 할 수 있습니다' 첫 번째 관계 '.

A life in the present is a present itself.

같은 문장은 숫자 1 안타로 'A'또는 '존재'중 하나를 발표 할 예정이다. 사실 사전은 (일반적으로) 순서가 매겨지지 않기 때문에 결과가 여러 번 반복되는 첫 단어가 아닐 수도 있습니다. 당신이 배수에보고해야하는 경우

, 나는 다음과 같은 제안 될 수 있습니다 '히트'

1) '단어'에 대한 키 - 값 쌍 현재의 방법을 사용합니다.
2) '히트'에 대한 최대 값을 결정하십시오.
3) 가장 많은 히트 수와 동일한 값의 수를 확인하고 해당 키를 목록에 추가하십시오.
4) 목록을 반복하여 조회수가 가장 많은 단어를 표시합니다.

파 예 :

greatestNumber = 0 
# establish the highest number for wordCounter.values() 
for hits in wordCounter.values(): 
    if hits > greatestNumber: 
     greatestNumber = hits 

topWords = [] 
#find the keys that are paired to that value and add them to a list 
#we COULD just print them as we iterate, but I would argue that this 
#makes this function do too much 
for word in wordCounter.keys(): 
    if wordCounter[word] == greatestNumber: 
     topWords.append(word) 

#now reveal the results 
print "The words that showed up the most, with %d hits:" % greatestNumber 
for word in topWords: 
    print word 

파이썬 2.7 파이썬 3에 따라, 귀하의 마일리지 (및 구문) 다를 수 있습니다.그러나 이상적으로 - IMHO - 가장 많은 수의 히트를 결정한 다음 돌아가서 관련 목록을 새 목록에 추가하려고합니다.

EDIT - 다른 답변에서 제안 된대로 카운터 모듈을 사용해야합니다. 나는 그것이 파이썬이 방금 준비한 것이 었는지도 몰랐다. 하하는 내 대답을 수락하지 않습니다. 반드시 자신의 카운터를 작성해야합니다! 이미 모듈이 있습니다.

2

자신의 카운터를 롤링하는 대신 컬렉션 모듈에서 Counters을 사용하는 것이 더 좋습니다. 또한

>>> input = 'blah and stuff and things and stuff' 
>>> from collections import Counter 
>>> c = Counter(input.split()) 
>>> c.most_common() 
[('and', 3), ('stuff', 2), ('things', 1), ('blah', 1)] 

, 일반적인 코드 스타일 것은,이 같은 의견을 추가 피해주십시오 : 그것은 더 코드가 덜 읽을 수 없습니다 수 있습니다

#Set option to 0. 
option = 0 

. 파이썬으로

+0

나는 이것이 어떤 것이 었는지 전혀 몰랐다. 이것은 아주 좋은 것입니다. –

0

당신이 statistics.mode을 사용할 수 있습니다 3.6 :

>>> from statistics import mode 
>>> mode('Hello I like pie because they are like so good'.split()) 
'like' 
관련 문제