How do I iterate through a string in Python? -
as example, lets wanted list frequency of each letter of alphabet in string. easiest way it?
this example of i'm thinking of... question how make alltheletters equal said letters without alltheletters = "abcdefg...xyz". in many other languages letter++ , increment way through alphabet, far haven't come across way in python.
def alphcount(text): lowertext = text.lower() letter in alltheletters: print letter + ":", lowertext.count(letter)
the question you've asked (how iterate through alphabet) not same question problem you're trying solve (how count frequency of letters in string).
you can use string.lowercase, other posters have suggested:
import string alltheletters = string.lowercase
to things way you're "used to", treating letters numbers, can use "ord" , "chr" functions. there's absolutely no reason ever this, maybe comes closer you're trying figure out:
def getalltheletters(begin='a', end='z'): beginnum = ord(begin) endnum = ord(end) number in xrange(beginnum, endnum+1): yield chr(number)
you can tell right thing because code prints true
:
import string print ''.join(getalltheletters()) == string.lowercase
but, solve problem you're trying solve, want use dictionary , collect letters go:
from collections import defaultdict def letteroccurrances(string): frequencies = defaultdict(lambda: 0) character in string: frequencies[character.lower()] += 1 return frequencies
use so:
occs = letteroccurrances("hello, world!") print occs['l'] print occs['h']
this print '3' , '1' respectively.
note works unicode well:
# -*- coding: utf-8 -*- occs = letteroccurrances(u"héĺĺó, ẃóŕĺd!") print occs[u'l'] print occs[u'ĺ']
if try other approach on unicode (incrementing through every character) you'd waiting long time; there millions of unicode characters.
to implement original function (print counts of each letter in alphabetical order) in terms of this:
def alphcount(text): character, count in sorted(letteroccurrances(text).iteritems()): print "%s: %s" % (character, count) alphcount("hello, world!")
Comments
Post a Comment