在一句含多个实例的字符串中搜索两个字词的索引(Python)

2024-06-16 18:08:29 发布

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

我需要一些关于这个我正试图用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()

Tags: inselfstringindexifdeftempword
1条回答
网友
1楼 · 发布于 2024-06-16 18:08:29

终于实现了

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()

相关问题 更多 >