python - counting tokens and characters in list -
say have following words want put in list
"cat,dog,fish" (first row) "turtle,charzard,pikachu,lame" (second row) "232.34,23.4,242.12%" (third row)
my question how count tokens in each line, first row has 3, second row has 4, third 1 has 3. after how count chracters, each row decide token has chracters? output looks like
token count = 3, character count = 10, fish has characters token count = 4, character count = 25, charzard has characters token count = 3, character count = 17, 242.12% has characters
only using simple list methods len(). , using comma delimiter. thanks, im lost because every time try strip comma using strip(',') error
try this. works both python2
, python3
rows = [ "cat,dog,fish", "turtle,charzard,pikachu,lame", "232.34,23.4,242.12%" ] row in rows: tokens = row.split(',') token_cnt = len(tokens) char_cnt = sum([len(token) token in tokens]) longest_token = max(tokens, key=len) print("token count = %d, character count = %d, %s has characters" %(token_cnt, char_cnt, longest_token))
results:
>>> token count = 3, character count = 10, fish has characters >>> token count = 4, character count = 25, charzard has characters >>> token count = 3, character count = 17, 242.12% has characters
edited:
now using max
instead of stupid choice of sort
find longest word, inspired @inspectorg4dget's answer.
Comments
Post a Comment