Set specific words in ScrolledText red - python

i need to find and highlight with color OR bold specific words in string.
i thought on doing like this
word to put in red=is:
var="my string is that should is appear with the word flame is in red is"
varf=var.replace(" is ","\033[1;32;40m is ")
but this dont work on tkinter ScrolledText, just in terminal :s
is there a way to do this in a tkinter ScrolledText widget?
Word will appear in diferent places in string so its hard to do the config.tag because i have to specify the interval of characters in the string to color.
my code
def checkval(e, spec0, spec1, spec2, spec3, spec4, spec5):
e.widget.insert("1.0", PLACEHOLDER if e.widget.get("1.0", "end-1c") == "" else "")
reqlidst=(spec0, spec1, spec2, spec3, spec4, spec5)
textlabl=""
for x in reqlidst:
if len(x)>1:
#print("selected text: '%s'" % e.widget.get(SEL_FIRST, SEL_LAST))
if x.upper() in e.widget.get("1.0", "end-1c").upper():
if len(textlabl)>1:
textlabl = textlabl + "- " + x.replace(" ", "").upper() + " " + html.unescape('✔')+"\n\n"
else:
textlabl = "- " + x.replace(" ", "").upper() + " " + html.unescape('✔')+"\n\n"
else:
if len(textlabl) > 1:
textlabl =textlabl + "- " + x.replace(" ", "").lower() + " " + html.unescape('✘')+"\n\n"
else:
textlabl = "- " + x.replace(" ", "").lower() + " " + html.unescape('✘')+"\n\n"
e.widget.my_var_expected.set(textlabl)
reqlidst are the word to search for and show in red
How to change the color of certain words in the tkinter text widget? doesnt answer my question :/

There is a tag method in the Tkinter text. This allows you to mark certain parts. I have prepared a small example for you, where the Text-Widget dynamically recognizes the words Hello and Jonny.
In principle, you only really need to be familiar with the indexes.
from tkinter import Text, Button, Tk
root = Tk()
def output(event):
length = len("Hello")
val = len(txt.get("1.0", "end-1c"))
for x in range(len(txt.get("1.0", "end-1c"))):
if "Hello" in txt.get(f"1.{x}", "end-1c") or "Jonny" in txt.get(f"1.{x}", "end-1c") :
val = x
vals = str(val + length)
txt.tag_add("Hello", f"1.{str(val)}", f"1.{vals}")
txt.tag_config("Hello", background="red", foreground="white")
txt = Text(root)
txt.grid(columnspan=3)
root.bind("<Key>", output)
root.mainloop()
enter image description here
Please note that I did not write a whole program for each new line.
For example, to make it more dynamic, you could change the indexes. So you can implement that for each line.
My example is for the first line only.
greeting

Related

How to split text into sentences by including corner cases

I am using this link for splitting text into sentences:
How can I split a text into sentences?.
Here is the code:
%%time
import re
alphabets= "([A-Za-z])"
prefixes = "(Mr|St|Mrs|Ms|Dr)[.]"
suffixes = "(Inc|Ltd|Jr|Sr|Co)"
starters = "(Mr|Mrs|Ms|Dr|He\s|She\s|It\s|They\s|Their\s|Our\s|We\s|But\s|However\s|That\s|This\s|Wherever)"
acronyms = "([A-Z][.][A-Z][.](?:[A-Z][.])?)"
websites = "[.](com|net|org|io|gov|ly)"
digits = "([0-9])"
def split_into_sentences(text):
text = " " + text + " "
text = text.replace("\n"," ")
text = re.sub(prefixes,"\\1<prd>",text)
text = re.sub(websites,"<prd>\\1",text)
text = re.sub(digits + "[.]" + digits,"\\1<prd>\\2",text)
if "Ph.D" in text: text = text.replace("Ph.D.","Ph<prd>D<prd>")
text = re.sub("\s" + alphabets + "[.] "," \\1<prd> ",text)
text = re.sub(acronyms+" "+starters,"\\1<stop> \\2",text)
text = re.sub(alphabets + "[.]" + alphabets + "[.]" + alphabets + "[.]","\\1<prd>\\2<prd>\\3<prd>",text)
text = re.sub(alphabets + "[.]" + alphabets + "[.]","\\1<prd>\\2<prd>",text)
text = re.sub(" "+suffixes+"[.] "+starters," \\1<stop> \\2",text)
text = re.sub(" "+suffixes+"[.]"," \\1<prd>",text)
text = re.sub(" " + alphabets + "[.]"," \\1<prd>",text)
if "”" in text: text = text.replace(".”","”.")
if "\"" in text: text = text.replace(".\"","\".")
if "!" in text: text = text.replace("!\"","\"!")
if "?" in text: text = text.replace("?\"","\"?")
text = text.replace(".",".<stop>")
text = text.replace("?","?<stop>")
text = text.replace("!","!<stop>")
text = text.replace("<prd>",".")
sentences = text.split("<stop>")
sentences = sentences[:-1]
sentences = [s.strip() for s in sentences]
if len(sentences)==0:
k=[]
return [text]
else:
return sentences
Though the above code works well for most of the corner cases. But if failed in few cases like:
text="Thank you for contacting back. Request you to please help us with the transaction ID for $<***>.92 ? - Charlie."
It breaks the $<***>.92 into $<***>. and 92. How can I include this in above code?
In case you want to extend your code, you can add the dollar sign ($) to the floating value parsing:
text = re.sub("$" + digits + "[.]" + digits,"\\1<prd>\\2",text)

How do i store a value in my txt file without it disappearing

import tkinter as tk
#The data does appear in the txt file. but after pressing the submitting button it doesnt stay there.
def submit():
outfile = open("text.txt", "w")
A = entry1.get()
B = entry2.get()
username = "UserName, "
password = "Password, "
C = username + A
D = password + B
outfile.write(C + " " + D)
entry1.delete(0, tk.END)
entry2.delete(0, tk.END)
#If i put a input and submit it will just be thr and not stored. how do i store the value in the txt file permently without it going away? Must i do a loop?
frame = tk.Tk()
tk.Label(text="Username").grid(row=1)
tk.Label(text="Password").grid(row=2)
entry1 = tk.Entry()
entry2 = tk.Entry()
entry1.grid(row=1 , column=1)
entry2.grid(row=2 , column=1)
tk.Button(frame, text="Submit" , command=submit).grid(row=3,column=0, pady=4)
frame.mainloop()
Your syntax is wrong. The correct way to write to a file is:
outfile.write(C + " " + D)
file.write is a function, not a variable.
So this
outfile.write = (C + " " + D)
should be
outfile.write(C + " " + D)
At the end, don't forget to close the file. Otherwise, it might not be saved.

Python run script when Tkinter button pressed

I am trying to make it so that the variable fpl is set when the button (command submit) is used. The problem is, it runs through the entire thing before the user has hit the button. How do i make it so the script beginning?
#Convert string to list
fpl = fpl.replace(" " , ".")
Is only run once the user has pressed the button? Rest of the code below.
import json
from tkinter import *
def submit():
fpl = entry.get()
window = Tk()
window.title ("Infinite FMS")
Label (window, text="Enter your flight plan
here:").grid(row=0,column=0,sticky=W)
entry = Entry(window, width = 75, bg = "light blue")
entry.grid(row=1,column=0,sticky=W)
Button (window, text="Submit",
command=submit).grid(row=2,column=0,sticky=W)
output = Text(window,width=75,height=6,background="light
blue")
output.grid(row=3,column=0,sticky=W)
#Convert string to list
fpl = fpl.replace(" " , ".")
"[" + fpl + "]"
fpllist = fpl.split(".")
#Length of fpllist
fpllen = len(fpllist)
#Loop through the flight plan missing first and last
entries
n = 1
Invalid = []
while n < fpllen - 1:
#Check for item in file
searchTerm = (fpllist[n])
searchTermF = "\'Name\': \'" + searchTerm + "\'"
searchTermV = "\'identifier\': \'" + searchTerm + "\'"
file = open('mydirectory', 'r')
data1 = json.load(file)
file.close()
file = open('mydirectory', 'r')
data2 = json.load(file)
file.close()
if searchTermF in str(data1):
Validity = "Your route is valid!"
n = n + 1
elif searchTermV in str(data2):
Validity = "Your route is valid!"
n = n + 1
else:
Validity = "Your route is invalid!\nInvalid
waypoints:"
Invalid.append(searchTerm)
n = n + 1
if len(Invalid) == 0:
print (Validity , ', '.join(Invalid))
else:
Validity = "Your route is invalid!\nInvalid
waypoints:"
print (Validity , ', '.join(Invalid))
output.delete(0.0, END)
output.insert(END, (Validity , ', '.join(Invalid)))
As PM 2Ring said if you put this
#Convert string to list
fpl = fpl.replace(" " , ".")
"[" + fpl + "]" #what is this supposed to do?
fpllist = fpl.split(".")
#Length of fpllist
fpllen = len(fpllist)
in your submit function it will be run when you click the button.
Also you don't need to replace the spaces with points fpllist = fpl.split() will give you the same result.
And you should really learn OOP(google it if you don't know what it is) it will make your program more readable and you can split diffrent parts of your program in diffrent functions.

How to create a new line using tkinter.Text()

I've tried appending a '/n' as shown in the code below however the output is still just one block of text that extends from one line to the next, rather than creating a new line after each list entry like I want
final_presentation_text = ["You are " + diet, "Your calorie limit
is " + str(calorie_count),
"Your diet has " + str(calorie_number),
" Your carbs target is " +
str(carbs_target),
" Your diet has " + str(carbs_number)]
for lines in final_presentation_text:
final_presentation.insert(1.0, lines + '/n')
It's backslash ("\") and then "n" for a new line, i.e. "\n", not forward slash.

Change the color result of text after being compared in PyQt4

I have a pretty easy question that i'm trying to wrap my head around why it's not working.
Basically I am trying to print out the result of my compare function and the results that DO NOT match in a different color.\
heres a sample of my code:
with open(compareResults, 'wb') as fdout:
for index, tabName in enumerate(setNames):
tabWidget = QtGui.QWidget()
tabLabel = QtGui.QTextEdit()
print "Tab Name is :{}".format(tabName)
fdout.write('{}'.format(tabName) + '\r\n')
nameData = lst[index]
print 'name data = {}'.format(nameData)
for k in nameData:
# if nameData[k] == 'ESS':
# print 'ESS found'
# elif nameData[k] != 'ESS':
if nameData[k] != correct_parameters[k]:
tabLabel.append('{} = {}'.format(k, nameData[k]))
tabLabel.setStyleSheet('color: black')
fdout.write('\t' + '|' + '{} = {}'.format(k, nameData[k]) + '\t' + '|' + '\r\n')
print ('{} = {}'.format(k, nameData[k]))
elif nameData[k] == correct_parameters[k]:
tabLabel.append('{} = {}'.format(k, nameData[k]))
tabLabel.setStyleSheet('color: red')
fdout.write('\t' + '|' + '{} = {}'.format(k, nameData[k]) + '\t' + '|' + '\r\n')
print ('{} = {}'.format(k, nameData[k]))
tabLayout = QtGui.QVBoxLayout()
tabLayout.addWidget(tabLabel)
tabWidget.setLayout(tabLayout)
self.tabWidget.addTab(tabWidget, tabName)
I want the text result that does match == to be in red and the result that doesn't match in black != however i believe the loop is over writing the results with the second elif so my result only appears in red and doesn't show the != result.
My what code does is compare two text documents that have a series of data and parameters in side of it. Once the program has compared both files it will output any result that are Different so for example if in main file (correct file) dog = 6 and in the other file (incorrect file) dog = 9 it will print out dog = 9 as in "Hey look dog in your other file is incorrect please fix it"
Currently my code does what it's suppose to and print out the incorrect values to my result however I just want to format it to have everything the incorrect values and the correct values. How can i color coat my results correctly?
Heres a visual representation of what am trying to achieve: As you can see Mouse is in black since it's incorrect and the result is in red since it's correct.
With tabLabel.setStyleSheet('color: red') you're changing the css of the whole QTextEdit: you define that all text, even previously written, will be red.
To change the color of the text, you can simply call setTextColor(QtGui.QColor) before writing.
For example:
self.text=QtGui.QTextEdit()
self.text.setTextColor(QtGui.QColor("blue"))
self.text.append("I'm blue !")
self.text.setTextColor(QtGui.QColor("red"))
self.text.append("I'm red !")

Categories