python 2.7 - Can't get counter to compare first letter of word against A-Z alphabet -
what i'm trying compare first letter of each word against lower case a-z alphabet , print (similar word_frequency) how many times word starts each letter of alphabet (such this)
a = 0 b = 2, c = 0, d = 2 ------------ y = 1, z = 0
but unable find way through counter of yet or found worked me (beginner). idea had along lines of
w in word_count: l_freq = [] l_freq.append(w[0])
and comparing counter against it? not sure how compare against whole alphabet rather letters in string?
also, there way print frequency cleaner? without counter , brackets showing up?
from collections import counter def function(): string = "this string written in python." word_count = string.split() char_count = 0 char in string: if char != " " , char != ".": char_count += 1 word_freq = counter(word_count) print "word count: " + str(len(word_count)) print "average length of word: " + str(char_count / len(word_count)) print "" print "word frequency: " print word_freq
let's have test data this:
in [1]: test_data = ''' ...: hello ...: hi ...: goodbye ...: bye ...: bye! ...: lol ...: lmao ...: rofl ...: '''
to count first letter of each word, you'd this:
counter = counter(w[0] w in test_data.split())
which you're doing. expected output think want, need associate each lowercase letter count, (import string
if haven't already):
for letter in string.ascii_lowercase: print letter, '=', counter[letter]
which test data showed gives you:
a = 0 b = 1 c = 0 d = 0 e = 0 f = 0 g = 1 h = 2 = 0 j = 0 k = 0 l = 2 m = 0 n = 0 o = 0 p = 0 q = 0 r = 1 s = 0 t = 0 u = 0 v = 0 w = 0 x = 0 y = 0 z = 0
Comments
Post a Comment