Mini Search engine Python(File finder and keyword finder) - python

I'm working on a search engine but I'm facing problems,I want like words from notepad to show on my 'search results', but it's not showing anything, and if you could help me doing like how many times the keyword that I'm searching for got repeated I would appreciate it this is the code:
from tkinter import *
import os
from tkinter.filedialog import askdirectory
from tkinter import messagebox
import subprocess
def content_analyser(pat):
with open(pat,'r') as f:
try:
for line in f:
if search in line:
d.update()
d.insert(END, pat)
break
except:
pass
def smali_finder(pat):
try:
for file in os.listdir(pat):
spat=pat+'/'+file
if os.path.isdir(spat):
smali_finder(spat)
else:
if file.endswith(".smali"):
content_analyser(spat)
except Exception as e:
print ("Error:::",pat,e)
def fing(path):
global search
if search_word.get()=='':
var=messagebox.showwarning(message="Please a search word")
else:
search=search_word.get()
smali_finder(path)
def save_list():
with open("saved_result","w") as sfile:
sfile.write('\n'.join(d.get(0,END)))
var=messagebox.showwarning(message="File names are saved as {}".format("saved_result.txt"))
def chose_folder():
global path
foldername = askdirectory()
path=foldername
folder_name.delete(0,END)
folder_name.update()
folder_name.insert(END, path)
if __name__=="__main__":
parent=Tk()
parent.title('File Finder')
Label(parent,text="Folder name: ").grid(row=0,column=0,sticky='e')
folder_name=Entry(parent,width=20)
folder_name.grid(row=0,column=1,padx=2,pady=2,sticky='we',columnspan=9)
Label(parent,text="Search word: ").grid(row=1,column=0,sticky='e')
search_word=Entry(parent,width=20)
search_word.grid(row=1,column=1,padx=2,pady=2,sticky='we',columnspan=9)
Label(parent,text="Search Results: ").grid(row=3,column=0,sticky='e')
d=Listbox(parent,width=125,height=20)
d.grid(row=4,column=3,padx=2,pady=2,sticky='we',columnspan=9)
Button(parent,text="Folder",command=lambda:chose_folder()).grid(row=0,column=10,sticky='e'+'w',padx=2,pady=2,)
start=Button(parent,text="Start",command=lambda:fing(path)).grid(row=1,column=10,sticky='e'+'w',padx=2,pady=2,)
save=Button(parent,text="Save",command=lambda:save_list())
save.grid(row=2,column=10,sticky='e'+'w',padx=2,pady=2)
Button(parent,text="Exit",command=parent.destroy).grid(row=3,column=10,sticky='e'+'w',padx=2,pady=2)
parent.mainloop()

Related

Python function return is none

I have a problem in my project. In my program I have the availability to choose more files if I want. The Problem is, that the return choosen_files has the list of the files but choosen_files which calls the more_files() method is none.
Do you have any suggestion?
Here is my code
import tkinter as tk
from tkinter import filedialog as fd
def get_files(path):
root = tk.Tk()
root.withdraw()
files = fd.askopenfilenames(
parent=root, title='Choose all files you want', initialdir=path)
return list(files)
def more_files(choosen_files, path):
print("choosen files:")
[print(file) for file in choosen_files]
wantMoreFiles = input(
"Do you want to choose more files? [(1) yes, (2) no]").lower()
if wantMoreFiles in ['1', 'y', 'yes']:
new_files = get_files(path)
choosen_files.extend(new_files)
more_files(choosen_files, path)
else:
return choosen_files
#this has the correct list
files = ['path/file1']
path = 'path'
choosen_files = more_files(files, path)
#this is none
Thank you very much!
You don't return anything on the last line.
Just return more_files(files, path)

how to connect gui and main code in python

I wanna make a dictionary program that could be run every platform. I coded it and it works basically, the user selects a word with a double click before clicking 'Q' and it gives selected word definition. Then I need a GUI. I made it but I couldn't connect them.
dict.txt's example : https://i.stack.imgur.com/Z9WMJ.png
Sceptral (a.) Of or pertaining to a scepter; like a scepter.
Scern (v.t.) To discern; to perceive.
Schade (n.) Shade; shadow.
Schah (n.) SeeShah.
Schediasm (n.) Cursory writing on a loose sheet.
main code;
import pyautogui as pya
import pyperclip
import time
import keyboard
import re
import sys
liste = list()
def copy_clipboard():
time.sleep(5)
pya.hotkey('ctrl', 'c')
time.sleep(.01)
return pyperclip.paste()
def click(key, *args,**kwargs): #
oldword = pyperclip.paste()
time.sleep(.01)
pya.hotkey('ctrl','c')
newword = pyperclip.paste()
time.sleep(.01)
pyperclip.copy(oldword)
capitalizing = newword.capitalize()
delete_space = capitalizing.strip()
word = delete_space
print(word)
file = open('dict.txt', 'r')
for line in file:
if word == line.split(" ")[0]:
letters = re.sub(word, " ", line)
liste.append(letters)
print(liste)
file.close()
while True:
try:
if keyboard.on_press_key('q',click):
print('You Pressed a Key!')
sleep(.01)
break
else:
pass
except:
break
gui;
import tkinter as tk
window = tk.Tk()
window.geometry("300x400+1200+200")
window.title("dict")
#window.wm_attributes("-alpha")
button = tk.Button(text = "Yuppi")
button.pack()
sbr = tk.Scrollbar(window)
sbr.pack(side=tk.RIGHT,fill="y")
text1 = tk.Text(window)
text1.insert(tk.INSERT, liste)#letters or liste has to be here
text1.pack()
window.mainloop()
Unfortunately connecting a GUI to a backend program requires a overhaul of the backend code. When you make a Tkinter GUI, a lot of the controls that you would usually use in backend, such as "print (…)" becomes more complicatd with tk.Label(window, text=…).place(x=x,y=y). So you will essentially have to incorporate your GUI into your backend code.

Using .split with tkinter

Quite a beginner here. I have a command line script that works fine for what I do and I'm looking to move it into a GUI.
os.chdir(ImageDirST)
for f in sorted(os.listdir(ImageDirST)):
f_name,f_ext = (os.path.splitext(f))
f_sku = (f_name.split(' ')[0])
f_num = (f_name[-2:])
n_name = ('{}_{}{}'.format(f_sku,f_num,f_ext))
print(f, "-->", n_name)
I would like this to display in the same fashion within a message window in tkinter.
With some help from here, I managed to print the filenames in the directory when a button is pushed with:
filenames = sorted(os.listdir(ImageDirBT))
text = "\n".join(filenames)
print_filename_test.set(text)
I have tried to use my split code to setup a list of what the new filenames would look like, prior to setting the variable, with the following, where print_filenames() is the function triggered by the press of a button.
def print_filenames():
filenames = sorted(os.listdir(ImageDirBT))
for filenames in sorted(os.listdir(ImageDirBT)):
f_name,f_ext = (os.path.splitext(filenames))
f_sku = (f_name.split('_')[0])
f_num = (f_name[-2:])
n_name = ('{}_{}{}'.format(f_sku,f_num,f_ext))
newlist = "\n".join(n_name)
print_filename_test.set(newlist)
I don't get any errors with this code for print_filenames(), however what is displayed in the message panel is the last filename in the list, vertically, one character wide:
eg:
F
I
L
E
_
1
1
.
e
x
t
I would like to display the output as:
oldfilename_01.ext --> newfilename_csvdata_01.ext
oldfilename_02.ext --> newfilename_csvdata_02.ext
oldfilename_03.ext --> newfilename_csvdata_03.ext
oldfilename_04.ext --> newfilename_csvdata_04.ext
The command line program I have written uses numbers to chose menu options for what needs to be done, confirming before any renaming is done, hence printing the file name comparisons. My struggle is manipulating the strings in the list to be able to do the same thing.
Using messagebox:
import os
import tkinter as tk
from tkinter import messagebox
ImageDirST = r"your_path"
os.chdir(ImageDirST)
root = tk.Tk()
names = []
for f in sorted(os.listdir(ImageDirST)):
f_name,f_ext = (os.path.splitext(f))
f_sku = (f_name.split(' ')[0])
f_num = (f_name[-2:])
n_name = ('{}_{}{}'.format(f_sku,f_num,f_ext))
names.append(f"{f} --> {n_name}\n")
messagebox.showinfo(title="Something", message="".join(names))
root.mainloop()
Or using Text widget with scrollbar:
import os
import tkinter as tk
from tkinter.scrolledtext import ScrolledText
ImageDirST = r"your_path"
os.chdir(ImageDirST)
root = tk.Tk()
txt = ScrolledText(root, font="Arial 8")
txt.pack()
for f in sorted(os.listdir(ImageDirST)):
f_name,f_ext = (os.path.splitext(f))
f_sku = (f_name.split(' ')[0])
f_num = (f_name[-2:])
n_name = ('{}_{}{}'.format(f_sku,f_num,f_ext))
txt.insert("end",f"{f} --> {n_name}\n")
root.mainloop()

Simple tkinter gui for already existing code

I have some already written code (btw I'm still a noob at python and programming in general) and i want to make a tkinter window that has a text box that is gonna show everything printed in the console and a button that is gonna run the main() function.
my existing code:
import pafy
import os
from pydub import AudioSegment
def downloadSound(videourl):
url = str(videourl)
video = pafy.new(url)
bestaudio = video.getbestaudio()
print(video.title, video.author, video.length)
bestaudio.download()
def linklister(linklist):
f = open('links.txt','r')
for line in f:
linklist.append(line.strip())
f.close()
def converter():
dirlist = os.listdir()
songlist = []
for i in dirlist:
if ".webm" in i:
songlist.append(i)
for i in songlist:
sound = AudioSegment.from_file(i)
imp3 = i.replace(".webm", ".mp3")
sound.export(imp3, format="mp3", bitrate="192k")
print (i, "DONE")
def main():
ytlinks = []
linklister(ytlinks)
for i in ytlinks:
downloadSound(i)
print ("downlad complete, proceeding to conversion")
converter()
try:
main()
except Exception as e:
print (e)
print ("OPPS")
else:
pass
I have not tested this but from personal experience this tkinter code works, I am unable to check if it works within yours. If this code doesn't work, test it by adding a print where I placed the comment.
import sys
import tkinter as tk
import pafy
import os
from pydub import AudioSegment
def downloadSound(videourl):
url = str(videourl)
video = pafy.new(url)
bestaudio = video.getbestaudio()
print(video.title, video.author, video.length)
bestaudio.download()
def linklister(linklist):
f = open('links.txt','r')
for line in f:
linklist.append(line.strip())
f.close()
def converter():
dirlist = os.listdir()
songlist = []
for i in dirlist:
if ".webm" in i:
songlist.append(i)
for i in songlist:
sound = AudioSegment.from_file(i)
imp3 = i.replace(".webm", ".mp3")
sound.export(imp3, format="mp3", bitrate="192k")
print (i, "DONE")
def main():
ytlinks = []
linklister(ytlinks)
for i in ytlinks:
downloadSound(i)
print ("downlad complete, proceeding to conversion")
class TextOut(tk.Text):
def write(self, s):
self.insert(tk.CURRENT, s)
def flush(self):
pass
if __name__ == '__main__':
root = tk.Tk()
text = TextOut(root)
sys.stdout = text
text.pack(expand=True, fill=tk.BOTH)
main()#here
root.mainloop()

Running a script for many files of the same extension and writing the results to a text file

I'm trying to write a script to extract data from a number of files in a directory with the extension ".tp6" and then write all of that data to a single text file.
It's able to get data from each file correctly and print them to the terminal, but I haven't been able to 'pass' each data point to another function that writes it to a text file.
Any ideas? Thank you!
import glob
import os
import Tkinter
import tkFileDialog
root = Tkinter.Tk()
root.withdraw()
dir_path = tkFileDialog.askdirectory()
os.chdir(dir_path)
def main():
for file_path in glob.glob('*.tp6'):
uncovext(file_path)
def main2():
for file_path in glob.glob('*.tp6'):
totext(uncovext)
#find and print data from each .tp6 file - this part works correctly
def uncovext(file_path):
for line in open(file_path):
if line.startswith(' UNCONVOLVED INTEGRATED RADIANCE'):
text = line[36:47]
number = float(text) * 10000
print('%.3f' % number)
def totext(uncovext):
with open("output.txt", "a") as f:
f.write(uncovext)
f.close()
if __name__ == '__main__':
main()
main2()
I think it was a matter of naming: if you change your input parameter of totext function to p_uncovext for example, it should work. You need also to call the function to text on your loop.
import glob
import os
import Tkinter
import tkFileDialog
root = Tkinter.Tk()
root.withdraw()
dir_path = tkFileDialog.askdirectory()
os.chdir(dir_path)
def main():
for file_path in glob.glob('*.tp6'):
uncovext(file_path)
#find and print data from each .tp6 file - this part works correctly
def uncovext(file_path):
for line in open(file_path):
if line.startswith(' UNCONVOLVED INTEGRATED RADIANCE'):
text = line[36:47]
number = float(text) * 10000
totext('%.3f' % number)
def totext(p_uncovext):
with open("output.txt", "a") as f:
f.write(p_uncovext)
f.close()
if __name__ == '__main__':
main()
You have a couple of problems. First uncovext doesn't save the data it parses from the input file. After printing to the screen, it is just thrown away. You could collect it into a list and return that for further processing. Then, you call the writer in a second function and you don't have any way for main to let main2 know what the data is.
An easy fix is a single function that calls uncovext and uses its result to call totext.
import glob
import os
import Tkinter
import tkFileDialog
root = Tkinter.Tk()
root.withdraw()
dir_path = tkFileDialog.askdirectory()
os.chdir(dir_path)
def main():
for file_path in glob.glob('*.tp6'):
totext(uncovext(file_path))
#find and print data from each .tp6 file - this part works correctly
def uncovext(file_path):
output = []
for line in open(file_path):
if line.startswith(' UNCONVOLVED INTEGRATED RADIANCE'):
text = line[36:47]
number = float(text) * 10000
output.append('%.3f\n' % number)
return output
def totext(uncovext):
with open("output.txt", "a") as f:
f.writelines(uncovext)
if __name__ == '__main__':
main()
You could also rewrite your parser as a generator and write code that I find more self-explanatory (that's just me though...)
def main():
with open('output.txt', 'a') as f:
for file_path in glob.glob('*.tp6'):
f.writelines(uncovext(file_path))
#find and print data from each .tp6 file - this part works correctly
def uncovext(file_path):
for line in open(file_path):
if line.startswith(' UNCONVOLVED INTEGRATED RADIANCE'):
text = line[36:47]
number = float(text) * 10000
yield '%.3f\n' % number

Categories