First attempts

From XPUB & Lens-Based wiki
Revision as of 19:34, 9 October 2015 by SN (talk | contribs)

OMG! My weird code works! (P.S. Week ago I didn't know Python exists)
updated 09_10_15 (search of most_popular and least_popular words added)
tumblr_nc4o8e06Ut1r93xiko1_r1_500.gif

import string
punct = set(string.punctuation + string.digits)
longest = None
shortest = None
popular_key = None
popular_value = None
nonpopular_key = None
nonpopular_value = None
text = raw_input('Enter some text:')
free_text = ''.join(x for x in text if x not in punct) # deleting all digits and punctuation marks
free_text = free_text.lower()
words = free_text.split() #making list named words
number = len(words)
total = 0
counts = {} #dictionary
for word in words:
	total = total + len(word) #counting number of letters
	if longest is None or len(word) > len(longest): #searching for longest word
		longest = word
	if shortest is None or len(word) < len(shortest): #searching for shortest word
		shortest = word
	counts[word] = counts.get(word,0) + 1 #filling dictionary
for word,count in counts.items():
	if popular_value is None or count > popular_value: #searching for most popular word
		popular_key = word
		popular_value = count
	if nonpopular_value is None or count < nonpopular_value: #searching for least popular word
		popular_key = word
		nonpopular_key = word
		nonpopular_value = count
if number < 1: #for no text entered
	print 'number of words:', number
	print 'end of program'
else:
	print 'number of letters:', total
	print 'number of words:', number
	print 'number of unique words', len(counts.keys()), ',', counts.keys()
	print 'most popular word is', popular_key, ',', popular_value
	print 'least popular word is', nonpopular_key, ',', nonpopular_value
	print 'longest word is:', longest, ',', len(longest)
	print 'shortest word is:', shortest, ',', len(shortest)
	print 'avarage word lenght is:', float(total)/number
	print 'end of program'