Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在具有多个实例的句子中搜索两个单词字符串的索引(Python)_Python_Python 3.x - Fatal编程技术网

在具有多个实例的句子中搜索两个单词字符串的索引(Python)

在具有多个实例的句子中搜索两个单词字符串的索引(Python),python,python-3.x,Python,Python 3.x,我需要一些关于这个我正试图用python编写的程序的帮助。当我搜索学士学位时:学士学位中的学士学位输出应该是[2,3]和[5,6],但我只得到[2,3] class FindString: def string1(self): self.main_string = "degree : bachelors degree in bachelors degree" self.sub_string = "bachelors degree" def count(self):

我需要一些关于这个我正试图用python编写的程序的帮助。当我搜索学士学位时:学士学位中的学士学位输出应该是[2,3]和[5,6],但我只得到[2,3]

class FindString:

  def string1(self):
    self.main_string = "degree : bachelors degree in bachelors degree"
    self.sub_string = "bachelors degree"

  def count(self):
    sequence = self.main_string
    item = self.sub_string
    a = []
    temp = []
    for word_m in item.split():
        print(word_m)
        for index, word in enumerate(sequence.split()):
            if word.lower() == word_m.lower():
                if a == []:
                    a.append(index)
                    print("a1----------",a)
                elif index == a[-1] + 1:
                        a.append(index)
                        print("a2----------",a)
                else:
                    if a not in temp:
                        temp.append(a)
                        print("a3-------",a)



    print("a------------", a)
s = FindString()
s.string1()
s.count()

终于实现了

class FindString:

 def string1(self):
    self.main_string = "degree : bachelors degree in bachelors degree"
    self.sub_string = "bachelors degree"

 def count(self):
    sequence = self.main_string
    item = self.sub_string
    a = []
    temp = []
    for index, word in enumerate(sequence.split()):
        flag = 'no'
        for word_m in item.split():
            if word.lower() == word_m.lower():
                if a == []:
                    a.append(index)
                if a != []:
                    if index == a[-1] + 1:
                        a.append(index)
                    else:
                        flag ='yes'

        if flag == 'no':
            if a not in temp and len(a) == len(item.split()):
                temp.append(a)
            a = []
    print("temp---------", temp)

s = FindString()
s.string1()
s.count()

代码中的缩进没有意义。在发布Python代码时,请确保准确地再现缩进。否则,您将在代码中引入新的错误。您应该反转循环。@khelwood抱歉,我是新手。@akp您能详细说明一下吗?[2,3]和[5,6]是预期的结果,但您目前得到了什么?