Utilize Functions (4.5-4.5.2)
In Python, function itself can be a parameter of functions.
>>> sent = ['Take', 'care', 'of', 'the', 'sense', ',', 'and', 'the', ... 'sounds', 'will', 'take', 'care', 'of', 'themselves', '.'] >>> def extract_property(prop): ... return [prop(word) for word in sent] ... >>> extract_property(len) [4, 4, 2, 3, 5, 1, 3, 3, 6, 4, 4, 4, 2, 10, 1] >>> >>> def last_letter(word): ... return word[-1] ... >>> extract_property(last_letter) ['e', 'e', 'f', 'e', 'e', ',', 'd', 'e', 's', 'l', 'e', 'e', 'f', 's', '.'] >>>
The next example is same behavior as last_letter() above.
>>> extract_property(lambda w: w[-1]) ['e', 'e', 'f', 'e', 'e', ',', 'd', 'e', 's', 'l', 'e', 'e', 'f', 's', '.']
Option of sort(). First 2 examples are same. "cmp" option is default and can be omitted. The last one is descending sorted by length.
>>> sorted(sent) [',', '.', 'Take', 'and', 'care', 'care', 'of', 'of', 'sense', 'sounds', 'take', 'the', 'the', 'themselves', 'will'] >>> sorted(sent, cmp) [',', '.', 'Take', 'and', 'care', 'care', 'of', 'of', 'sense', 'sounds', 'take', 'the', 'the', 'themselves', 'will'] >>> sorted(sent, lambda x, y: cmp(len(y), len(x))) ['themselves', 'sounds', 'sense', 'Take', 'care', 'will', 'take', 'care', 'the', 'and', 'the', 'of', 'of', ',', '.'] >>>
The result of search1() and search2() are same.
>>> def search1(substring, words): ... result = [] ... for word in words: ... if substring in word: ... result.append(word) ... return result ... >>> def search2(substring, words): ... for word in words: ... if substring in word: ... yield word ... >>> for item in search1('zz', nltk.corpus.brown.words()): ... print item ... Grizzlies' fizzled ....
The difference can be seen when try followings.
>>> search2('zz', nltk.corpus.brown.words()) <generator object search2 at 0x1024acd70> >>> searchi('zz', nltk.corpus.brown.words()) ["Grizzlies'", 'fizzled', 'Rizzuto', 'huzzahs', 'dazzler', ....
This function is to display all combinations of listed words.
>>> def permutations(seq): ... if len(seq) <= 1: ... yield seq ... else: ... for perm in permutations(seq[1:]): ... for i in range(len(perm) + 1): ... yield perm[:i] + seq[0:1] + perm[i:] ... >>> list(permutations(['police', 'fish', 'buffalo'])) [['police', 'fish', 'buffalo'], ['fish', 'police', 'buffalo'], ['fish', 'buffalo', 'police'], ['police', 'buffalo', 'fish'], ['buffalo', 'police', 'fish'], ['buffalo', 'fish', 'police']]