Problem: Using recursion it should go through all folders and files and search for a specific word. If you find a match then you should print path to file and line order is on. Finally, print out how many folders and files you have searched through and the number of times the word has appeared in the files.
I find this problem difficult and need some help. My code contain errors, but I am not sure how to solve these problems. Two of my errors: My solution does not count the occurrence of words correct, any tips? Pressing Search results in output in terminal, not in GUI-window.
from tkinter import * # Import tkinter
from tkinter.filedialog import askopenfilename
import os
def findInFile(filename, word1):
try:
if not os.path.isfile(filename):
list = os.listdir(filename)
for i in range(len(list)):
findInFile(list[i], word1)
text.insert(END, findInFile())
else:
findWord(filename, word1)
except:
print("Error")
def findWord(filename, word1):
try:
infile = open(filename,"r")
for line in infile:
if line.find(word1)>0:
print(filename+ ": " + line)
except:
return "No words"
def processLine(filename, word1): # count words
wordCounts = {} # Create an empty dictionary to count words
for line in filename:
pairs = list(wordCounts.items()) # Get pairs from the dictionary
items = [[count, word] for (word, count) in pairs]
items.sort(reverse = True) # Sort pairs in items
line = replacePunctuation(line) # Replace punctuation with space
words = line.split() # Get words from each line
for word in words:
if word in wordCounts:
wordCounts[word] += 1 # Increase count for word
else:
wordCounts[word] = 1 # Add an item in the dictionary
# Replace punctuation in the line with space
def replacePunctuation(line):
for ch in line:
if ch in "~@#$%^&*()_-+=~<>?/,.;:!{}[]|'\"":
line = line.replace(ch, " ")
return line
def getNumberOfFiles(filename):
size = 0
if not os.path.isfile(filename):
list = os.listdir(filename)
for i in range(len(list)):
size += getNumberOfFiles(filename + "\\" + list[i])
else:
size += 1
return size
# def directory_contents():
# call on root/top-level folder first, then loop through those contents,
# if a folder is found call the folder_contents on that folder,
# if a file is found then use the search_file function to search for
# occurrences of the word and return that number.
# def search_file():
def showResult():
print("\n\nSearch start.")
print("-----------------------")
print(findInFile(filename.get(), word1.get()))
print("-----------------------")
print("Search end. ")
print("Searched: directories and", getNumberOfFiles(filename.get()), "file(s), found", processLine(filename.get(), word1.get()), "occurences of", word1.get())
def openFile():
filenameforReading = askopenfilename()
filename.set(filenameforReading)
window = Tk() # Create a window
window.title("Find word in files") # Set title
frame1 = Frame(window) # Hold four labels for displaying cards
frame1.pack()
Label(frame1, text="Filename or directory: ").pack(side=LEFT)
filename = StringVar()
Entry(frame1, width=20, textvariable=filename).pack(side=LEFT)
Button(frame1, text="Browse", command=openFile).pack(side=LEFT)
Label(frame1, text="Enter a word ").pack(side=LEFT)
word1 = StringVar()
Entry(frame1, width=20, textvariable=word1).pack(side=LEFT)
Button(frame1, text="Search", command=showResult).pack(side=LEFT)
frame2 = Frame(window)
frame2.pack()
text = Text(frame2, width=100, height=30)
text.pack()
window.mainloop()
def findWord(filename, word1):
try:
infile = open(filename,"r")
data=infile.read()
line=data.count(word1)
#for line in infile:
# if line.find(word1)>0:
line=str(line)
return filename+ ": " + line
except:
return "No words"
def showResult():
print("\n\nSearch start.")
print("-----------------------")
print(findWord(filename.get(), word1.get()))
print("-----------------------")
print("Search end. ")
print("Searched: directories and", getNumberOfFiles(filename.get()), "file(s), found", processLine(filename.get(), word1.get()), "occurences of", word1.get())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.