sentence2 = raw_input("Enter the sentence on the StringLab3 WS: ")
sentence.split(sentence2)
for word in default_sentence:
if word == (chr(84)+chr(104)+chr(101)) or (chr(116)+chr(104)+chr(101)):
words += 1
print "The amounf of times 'the' or 'The' appear is a total of", words, "times."
This is what I have now, the output is currently 961 for the sentence:
This is a day of national consecration. And I am certain that on this day my fellow Americans expect that on my induction into the Presidency, I will address them with a candor and a decision which the present situation of our people impels. This is preeminently the time to speak the truth, the whole truth, frankly and boldly. Nor need we shrink from honestly facing conditions in our country today. This great Nation will endure, as it has endured, will revive and will prosper. So, first of all, let me assert my firm belief that the only thing we have to fear is fear itself, nameless, unreasoning, unjustified terror which paralyzes needed efforts to convert retreat into advance. In every dark hour of our national life, a leadership of frankness and of vigor has met with that understanding and support of the people themselves which is essential to victory. And I am convinced that you will again give that support to leadership in these critical days.
We're supposed to have the user input this. Any advice?
I'd recommend this:
Output:
Since my solution may look weird, here's a little explanation from left to right:
map(function, target)
: This applies the function to all elements oftarget
, thustarget
must be a list or some other iterable. In this case, we're mapping alambda
function, which can be a little scary, so read below about that.lower()
: Takes the lower case of whatever string its applied to,word
in this case. This is done to ensure that "the", "The", "THE", "ThE", and so on are all counted.split()
: This splits a string (paragraph
) into a list by the separator supplied in the parenthesis. In the case of no separator (such as this one), a space is assumed to be the separator. Note that sequential separators are lumped when the separator is left out..count(item)
: This counts the instances ofitem
in the list its applied to. Note that this is not the most efficient way to count things (gotta go regex if you about speed)The scary lambda function:
lambda functions are not easy to explain or understand. Its taken me quite a while to get a grip on what they are and when they're useful. I found this tutorial to be rather helpful.
My best attempt at a tl;dr is lambda functions are small, anonymous functions that can be used for convenience. I know this is, at best, incomplete, but I think it should suffice for the scope of this question