How to use find function to find all indexes in loop?

Viewed 37
from functools import partial


def x_in_y(word, inner):
    return inner in word


workbook = xlsxwriter.Workbook('result.xlsx')
worksheet = workbook.add_worksheet()
sentence=['yns, we have to clase windows explorer, and yns, we do not need to clase the case.']
words = [('yns','yes'),('clase','close')]


row = 0

red = workbook.add_format({'font_color': 'red'})
black = workbook.add_format({'font_color': 'black'})

for wrong, correct in words:
    filtered_names = filter(partial(x_in_y, inner=wrong), sentence)
    next_elem = next(filtered_names, None)

    if next_elem:
        while next_elem:
            if len(next_elem) == len(wrong):
                worksheet.write(row, 0, next_elem, red)
            else:
                slices = []
                startIndex = 0
                index = next_elem.find(wrong)
                print(index)
                while index != -1:
                    if next_elem[startIndex: index]:
                        slices.append(black)
                        slices.append(next_elem[startIndex: index])
                    slices.append(red)
                    slices.append(next_elem[index: index + len(wrong)])
                    startIndex = index + len(wrong)
                    index = next_elem.find(wrong, startIndex)

                if next_elem[startIndex:]:
                    slices.append(black)
                    slices.append(next_elem[startIndex:])

                worksheet.write_rich_string(row, 0, *slices)
            row += 1
            next_elem = next(filtered_names, None)
workbook.close()

Question: I'm writting a code that can create one excel file with typos indicated in red. For now, i could only identify one kind of typo for each sentences.

I guess the problem is that when I use "index = next_elem.find", I failed to find all index for wrong. What i expect is to find all typos in one sentence.

I don't want the same sentence need to be spitted into two results.

Current result:

enter image description here

I hope this:

enter image description here

0 Answers
Related