在类的方法中实现一个类元组

2024-09-26 22:55:01 发布

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

我想了解的是如何在方法中实现类元组“excludedWords”,以便方法忽略它们。我尝试过使用split方法,并尝试调用tuple,不管它是self.excludedWords还是split方法中的pose.excludedWords

class Prose:
    excludedWords = ('is', 'the', 'are', 'we', 'they', 'it', 'he', 'she')

    def __init__(self, words):
        self.prose = words

    def __str__(self):
        return str(self.prose)

    def numberOfWords(self):
        return len(self.prose.split())

    def distinctWords(self):
        return len(self.prose.split(self.prose)) 

    def toString(self):
        for words in self.prose.split():
            print(words)

    def __sub__(self, other):
        if self.prose != other.prose:
            newprose = self.prose.split(other.prose)
            otherprose = other.prose.split(self.prose)
            return newprose
        else:
            return self.prose 

    def newDict(self):
        myDict = {}
        myProse = self.prose.split()
        for word in myProse:
            if word in myDict:
               myDict[word] += 1
            else:
               myDict[word] = 1
        return myDict

Tags: 方法inselfforlenreturndefmydict
1条回答
网友
1楼 · 发布于 2024-09-26 22:55:01
def __init__(self, words):
    self.prose = words
    self.filtered_prose = ' '.join([w for w in words.split() if w not in excludedWords])

这将过滤掉任何你想在开头排除的词。 注意,如果标点符号跟在一个被排除的词后面,比如"is,",它不会排除这个词

相关问题 更多 >

    热门问题