#!/usr/bin/python
string_to_search = raw_input("Enter text to search: ")
print ''.join(filter(lambda x: x.isalpha(), string_to_search)) Here we are asking the user to enter the text or string that they want to search through. The second line can be a little more confusing. We are using the join command as an append function to add together any alpha characters that are returned. The filter function will only filter out what is define in the function following it, the lambda function. The lambda x is way to create inline function within Python and in this case to search for anything that is an alpha character. This function will work for relatively long string however if you are parsing a really long text item or one that contains special characters which the bash shell will attempt to interpret, I suggest you modify this script slight to read the characters from a text file and parse from there.
Sunday, April 4, 2010
Needle In a Haystack
Recently I was working through a coding challenge online which involved Python coding. One challenge required the user to parse a string of text for rare characters. After studying a cryptography course in college I knew the challenge was looking for frequencies, or the number of times each character appear in the string. Given the parameters that they want only the rare characters in the string I was looking for the characters that appeared the least. A quick Python script and i was good to go:
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment