[英]Searching for indexes of a two word string in a sentence with multiple instances of it(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()
終於設法實現了
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.