使用字符串方法理解代码

2024-06-02 07:31:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力理解一段代码,这是一个更大的问题集的一部分。代码如下(注意,WordTriggerTrigger的一个子类):

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

所以第5行的工作就是去掉文本中的标点符号,并将其变为小写。string.split(" ")方法创建文本中所有单词的列表,将它们拆分并在它们之间插入空格。for语句检查“word”是否在“text”中。那么它是否从构造函数中识别变量“word”?你知道吗

self.word.lower()是否使构造函数初始化的单词全部小写?“for”循环中的“if”条件是否确保搜索“alert”单词时不排除带撇号的单词?你知道吗


Tags: 代码textinselfforstringreturnif
2条回答

So does it recognizes the variable 'word' from the constructor?

不可以。方法中定义的变量是该方法的局部变量,对象属性(如self.word)不会与局部变量(如word)混淆。你知道吗

Does self.word.lower() make the word that was initialized by the constructor all lowercase?

不,字符串在Python中是不可变的。它返回一个新字符串self.word的小写版本。你知道吗

And does the 'if'-conditional in the 'for' loop make sure the search for 'alert' words doesn't exclude words with apostrophes?

在我看来是对的。你知道吗

第一个问题:for语句检查“word”是否在“text”中。那么它是否从构造函数中识别变量“word”?你知道吗

for语句的word是一个局部变量,与self.word不同。实际上,如果您愿意,您可以用item或任何变量名替换for循环。你知道吗

第二个问题:是吗self.word.lower下()使构造函数初始化的单词全部小写?你知道吗

不,不是因为他们是两个不同的东西。word局部变量是列表text中的每个项。self.word是第一次实例化时传递给WordTrigger对象的变量。你知道吗

相关问题 更多 >