I'm struggling with understanding a piece of code that's part of a larger problem set. The code is as follows (Note that WordTrigger is a subclass of Trigger):
class WordTrigger(Trigger):
def __init__(self,word):
self.word=word
def isWordin(self, text):
text = [a.strip(string.punctuation).lower() for a in text.split(" ")]
for word in text:
if self.word.lower() in word.split("'"):
return True
return False
So line 5 does the job of stripping the text of punctuation and making it lowercase. The string.split(" ") method creates a list of all the words in the text, splitting them and inserting blank spaces in between. The for-statement checks to see whether the 'word' is in the 'text'. So does it recognizes the variable 'word' from the constructor?
Does self.word.lower() make the word that was initialized by the constructor all lowercase? And does the 'if'-conditional in the 'for' loop make sure the search for 'alert' words doesn't exclude words with apostrophes?
2 Answers 2
So does it recognizes the variable 'word' from the constructor?
No. Variables defined within a method are local to that method, and object attributes (like self.word are not confused with local variables (like word).
Does self.word.lower() make the word that was initialized by the constructor all lowercase?
No. Strings are immutable in Python. It returns a new string -- a lower-cased version of self.word.
And does the 'if'-conditional in the 'for' loop make sure the search for 'alert' words doesn't exclude words with apostrophes?
Seems right to me.
4 Comments
word and self.word are different. The code would be less confusing if the variable names were changed a bit: for example, text_words rather than text, and then for tw in text_words.1st Question: The for-statement checks to see whether the 'word' is in the 'text'. So does it recognizes the variable 'word' from the constructor?
The for statement's word is a local variable and is not the same as self.word. You can essentially replace that for loop with item or any variable name if you like.
2nd Question: Does self.word.lower() make the word that was initialized by the constructor all lowercase?
No it doesn't because they are two different things. the word local variable is each item in the list text. and self.word is the variable you pass in to the WordTrigger object when you first instantiate it.