我有一个python类,允许用户选择文件列表然后读取文件并搜索请求的单词。
问题是我能够选择文件并阅读,但我无法搜索单词。
我将显示功能:
代码显示包含
的窗口 from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import (QApplication, QCheckBox, QColorDialog, QDialog,
QErrorMessage, QFileDialog, QFontDialog, QFrame, QGridLayout,
QInputDialog, QLabel, QLineEdit, QMessageBox, QPushButton)
from PyQt5.QtCore import QDir, Qt
from PyQt5.QtWidgets import *
import os,time,re
import pdfviewer
class pdfViewer(pdfviewer.Ui_PdfPreviewWindow):
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)
'''
search for entered string using regular expression in the lineEditSearch
==> highlight the requested word
==> display number of occurence of the searched word
'''
def searchWord(self,selectedFile):
fileToSearchInside = self.readFile(selectedFile)
searchedSTR = self.lineEditSearch.text()
# i think the error is here but i do not know how to fix it
while fileToSearchInside>0:
try:
if(searchedSTR in fileToSearchInside):
print("matched string")
except Exception as e:
print(e)
'''
read file based on the user click
'''
def readFile(self, currentFile):
currentFile = self.listWidgetPDFlist.currentItem().text()
print(currentFile)
try:
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))
'''
get the name of the current item selected in the list (==>the path name )
set in the edit text the selected item (==> selected file)
'''
def previewSelectedFile(self):
Item=self.listWidgetPDFlist.currentItem().text()
self.textEdit_PDFpreview.setText(self.readFile(Item))
答案 0 :(得分:0)
问题在于代码的逻辑。
所以在系统读完文本内容并分配给变量
之后我们只需要创建条件以检查所请求的单词是否存在。
所以解决方案从 searchWord函数
中删除 while循环。答案 1 :(得分:0)
这里有一个无限循环:
while fileToSearchInside>0:
try:
if(searchedSTR in fileToSearchInside):
print("matched string")
except Exception as e:
print(e)
file.read(n)从文件中读取n个字符,如果n为空,则读取整个文件。 所以你可以改变上面的行:
if searchedSTR in fileToSearchInside:
print("matched string")
为了匹配上面注释中显示的要求,您可以插入以下功能:
import re
occ_founded = re.findall(searchedSTR, fileToSearchInside, re.M)
通过这种方式,您可以在文件中创建一个单词列表,以及这些出现次数