Как добавить список файлов на основе подходящих слов

У меня есть класс Python, который позволяет пользователю выбрать путь для отображения файлов, а затем пользователь вводит искомое слово, чтобы сопоставить его со всеми перечисленными файлами.

как только пользователь нажмет на кнопку поиска, мне нужна система

  1. читать перечисленные файлы
  2. переопределить список, просто отображая файлы, которые имеют соответствующие

Система отображает эту ошибку:

searchWord self.listWidgetPDFlist.addItems (listFiles)

builtins.TypeError: индекс 0 имеет тип "bool", но ожидается "str"

для этой задачи я написал 3 функции

функция инициализации

def __init__(self,PdfPreviewObj):
        #QWidget.__init__(self)
        self.PdfPreviewObj =PdfPreviewObj 
        self.setupUi(PdfPreviewObj)
        self.PdfPreviewObj.show()
        self.pushButtonOpenFolder.clicked.connect(self.setExistingDirectory)
        self.pushButtonSearch.clicked.connect(self.searchWord)

функция readFile

def readFile(self, currentFile):
    try:
        currentFile = self.listWidgetPDFlist.currentItem().text()
        print(currentFile)

        with open(currentFile) as ctf:
            ctfRead = ctf.read()
            print(ctfRead)
            return(ctfRead)

    except Exception as e:
        print("the selected file is not readble because :  {0}".format(e))     

функция displayFilteredFile

    def displayFilteredFiles(self, filteredFiles):
            try:

                filteredFiles = self.listWidgetPDFlist.items()
                print(filteredFiles)
                for  file in filteredFiles:
                    with open(file) as ctf:
                        ctfRead = ctf.read()
                        print(ctfRead)
                    return(ctfRead)

            except Exception as e:
                print("the selected file is not readble because :  {0}".format(e))     

функция seachedWord

 def searchWord(self,filteredFiles): 

        listFiles = []
        self.textEdit_PDFpreview.clear()

        self.listWidgetPDFlist.clear()
        listFiles.append(filteredFiles)

       # here the system indicate the error 
        self.listWidgetPDFlist.addItems(listFiles)

        filesToSearchInside = self.displayFilteredFiles(listFiles)
        searchedSTR = self.lineEditSearch.text()
        RepX="<b><span style='color:white;mso-themecolor:background1;background:black;mso-highlight:black'>"+searchedSTR+'</span></b>'

        try:
            textList = filesToSearchInside.split('\n')

            # utility that gives an empty list for each key by default
            d = defaultdict(list)   

            '''
            looping over the selected text and search for the required word in the search box 
            store the word and the number of occurence in a dictionnary  to used for later.
            '''
            for counter, myLine in enumerate(textList):
                thematch=re.sub(searchedSTR,RepX,myLine)
                matches = re.findall(searchedSTR, myLine, re.MULTILINE | re.IGNORECASE)
                if len(matches) > 0:

                    # add one record for the match (add one because line numbers start with 1)
                    d[matches[0]].append(counter + 1)


                    self.textEdit_PDFpreview.insertHtml(str(thematch))
                    #self.textEdit_PDFpreview.insertHtml(result)



                # print out 
            for match, positions in d.items():
                print('{} exists {} times'.format(match, len(positions)))
                for p in positions:
                    print("on line {}".format(p))

        except Exception as e:
                print(e)        

0 ответов

Другие вопросы по тегам