2016-10-11 2 views
-1
>>> words=input('enter your sensence:') 
enter your sensence:it was the best of times it was the worst of times it was the age of wisdom it was the age of foolishnes 
>>> wordcount={} 
>>> for word in words.split(): 
    if word not in wordcount: 
     wordcount[word] = 1 
    else: 
     wordcount[word] += 1 


>>> print(word, wordcount) 
foolishnes {'age': 2, 'of': 4, 'it': 4, 'wisdom': 1, 'was': 4, 'the': 4, 'worst': 1, 'times': 2, 'foolishnes': 1, 'best': 1} 
+0

BTW, Die Schleife kann durch eingebautes 'Counter' ersetzt werden:' wordcount = collections.Counter (words.split()) ' – zvone

Antwort

0

Sie bereits Ihre wordcounts haben hier, wie Sie sie aus in sortierter Reihenfolge drucken würde.

def printout(wordcount): 
    for k in sorted(wordcount, key=lambda k: (wordcount[k], k)): 
     print(k, wordcount[k]) 
+0

danke Inspektor – johnb

+0

Wie kann man die Ergebnisse in einer Zeile ausgeben? – johnb

+0

@johnb:' print (k, wordcount [ k]), Ende = '') ' – inspectorG4dget

Verwandte Themen