python - Finding average word length in a string -


def word_count (x: str) -> str:     characters = len(x)     word = len(x.split())     average = sum(len(x) x in word)/len(word)     print('characters: ' + str(char) + '\n' + 'words: ' + str(word) + '\n' + 'avg word length: ' + str(avg) + '\n') 

this code works fine normal strings, string like:

'***the ?! quick brown cat:  leaps on sad boy.' 

how edit code figures "***" , "?!" aren't accounted in code? average word count of sentence above should turn out 3.888889, code giving me number.

try this:

import re  def avrg_count(x):     total_chars = len(re.sub(r'[^a-za-z0-9]', '', x))     num_words = len(re.sub(r'[^a-za-z0-9 ]', '', x).split())     print "characters:{0}\nwords:{1}\naverage word length: {2}".format(total_chars, num_words, total_chars/float(num_words))   phrase = '***the ?! quick brown cat:  leaps on sad boy.'  avrg_count(phrase) 

output:

characters:34 words:9 average word length: 3.77777777778 

Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -