试图从文本中删除句子列表,只删除第一个ch

2024-04-26 18:56:33 发布

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

我上了下面的课

class SentenceReducer():
    def getRidOfSentences(self, line, listSentences):
        for i in listSentences:
            print(i)
            return line.replace(i, '')

    strings = 'This is a'
    def stripSentences(self, aTranscript):
        result = [self.getRidOfSentences(line, self.strings) for line in aTranScript]
        return(result)

它基本上应该吃一个数据帧,然后每行检查相关行是否包含ListSequences中的一个句子(本例中为1)

但是当我创建一个新类时

newClass = SentenceReducer()

并使用以下数据运行脚本

aTranScript = [ 'This is a test', 'This is not a test']
new_df = newClass.stripSentences(aTranScript)

它删除了原始数据中的'T'。但它应该取代整个句子('This is a')。另外,如果我添加print(i),它会打印T

你觉得这里出了什么问题吗


Tags: inselfforreturnisdeflinethis
2条回答

首先,aTranscriptaTranScript不是同一个变量(注意后者的大写字母s

其次,应该使用self.listSentencesSentenceReducer.listSentences访问listSentences

第三,您使用的string没有在任何地方声明

最后,函数stripSentences不返回任何内容

getRidOfSentences内部,变量listSentences具有值'This is a',这是一个字符串

对字符串进行迭代会得到单个字符:

>>> strings = 'This is a'
>>> for x in strings:
...     print(x)
T
h
i
s

i
s

a

您希望将此字符串放入一个列表,以便在该列表上迭代得到整个字符串,而不是单个字符:

>>> strings = ['This is a']
>>> for x in strings:
...     print(x)
This is a

另一个问题:for循环中的return意味着函数在第一次迭代结束时退出,这就是为什么您只看到T,而看不到his等等

相关问题 更多 >