Skip to content

Instantly share code, notes, and snippets.

@secemp9
Created January 20, 2024 18:15
Show Gist options
  • Save secemp9/fc917c1378bbbcb7957b44f5e369ba9f to your computer and use it in GitHub Desktop.
Save secemp9/fc917c1378bbbcb7957b44f5e369ba9f to your computer and use it in GitHub Desktop.
tkinter random word replace
import tkinter as tk
from tkinter import scrolledtext
import requests
import random
import re
def fetch_text(url):
try:
response = requests.get(url)
response.raise_for_status()
return response.text
except requests.RequestException as e:
return str(e)
def replace_random_words():
max_words = int(max_words_entry.get())
original_text = text_widget.get("1.0", tk.END)
words = re.findall(r'\b\w+\b', original_text)
if max_words > len(words):
max_words = len(words)
# Calculate the interval for replacements
interval = len(words) // max_words
# Select words to replace at regular intervals
words_to_replace = [words[i] for i in range(0, len(words), interval)]
modified_text = original_text
for word in words_to_replace:
modified_text = re.sub(r'\b{}\b'.format(re.escape(word)), '___', modified_text, count=1)
root.update_idletasks()
root.update()
text_widget.delete("1.0", tk.END)
text_widget.insert(tk.INSERT, modified_text)
def main():
global root, text_widget
# URL of a Project Gutenberg text file (example: Pride and Prejudice)
url = 'http://www.gutenberg.org/files/1342/1342-0.txt'
# Fetch text
text = fetch_text(url)
# Create a Tkinter window
root = tk.Tk()
root.title("Gutenberg Text Viewer")
# Create a scrolled text widget
text_widget = scrolledtext.ScrolledText(root, wrap=tk.WORD)
text_widget.pack(fill=tk.BOTH, expand=True)
text_widget.insert(tk.INSERT, text)
# Create a frame for input and button
frame = tk.Frame(root)
frame.pack(fill=tk.X)
# Create an entry widget
global max_words_entry
max_words_entry = tk.Entry(frame)
max_words_entry.pack(side=tk.LEFT, expand=True, fill=tk.X)
# Create a button to trigger the replacement
replace_button = tk.Button(frame, text="Replace Words", command=replace_random_words)
replace_button.pack(side=tk.RIGHT)
root.mainloop()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment