Python — Генератор поиска слов — форматирование и позиционирование страницыPython

Программы на Python
Ответить
Anonymous
 Python — Генератор поиска слов — форматирование и позиционирование страницы

Сообщение Anonymous »

Я пытаюсь разработать программу, которая будет генерировать 2 поиска слов и списки слов на странице на основе списка слов из импортированного текстового файла и на основе значений, указанных в двух подсказках о том, сколько запросов слов нужно сгенерировать. и сколько слов должно содержать каждое слово из импортированного списка слов. Затем страницы будут экспортированы в файл изображения jpg в ту же папку, что и сценарий.
Мне удалось частично заставить это работать. У меня возникают проблемы следующим образом: -
  • Однако на каждой странице оба поиска слов содержат одни и те же слова, а не разные уникальные слова, каждая страница уникальна тем, что слова на странице 1 не совпадают со словами на странице 2.
  • Форматирование (цвет, жирный шрифт, подчеркивание и т. д.) заголовка на каждой странице "Слово" Необходимо выполнить поиск: 1", и я не могу найти способ его изменить.
  • Форматирование (цвет, жирный шрифт, подчеркивание и т. д.) заголовка на каждой странице списка слов Необходимо выполнить команду «Найди эти слова ниже!...», и я не могу найти способ изменить ее.
  • Выравнивание поиска слов и списков слов не по центру. страницы и должен располагаться в центре как по вертикали, так и по горизонтали и быть увеличенным, чтобы заполнить всю страницу (размеры страницы — 2550 x 3300 пикселей)
Мой код Python ниже:-

Код: Выделить всё

import random
import string
import os
from PIL import Image, ImageDraw, ImageFont
from tkinter import Tk, filedialog
import subprocess
import sys

# Ensure required packages are installed
def install_required_packages():
try:
import PIL
except ImportError:
print("Installing required Package: Pillow...")
subprocess.check_call([sys.executable, "-m", "pip", "install", "pillow"])

# Run the package installation
install_required_packages()

# Constants
GRID_SIZE = 20  # 20 for 20 x 20 grid
FONT_SIZE = 24  # Font size for text
CELL_SIZE = 50  # Cell size in pixels
GRID_BORDER_COLOR = (200, 200, 200)  # Light grey color for grid borders
TEXT_COLOR = (0, 0, 0)  # Black color for text
PAGE_SIZE = (2550, 3300)  # A4 size at 300 DPI (pixels)
PAGE_WIDTH_INCHES = 8.5
PAGE_HEIGHT_INCHES = 11
DPI = 300
FONT_PATH = "C:/Windows/Fonts/Verdana.ttf"  # Path to Verdana font

# Validate font path
if not os.path.exists(FONT_PATH):
raise FileNotFoundError(f"Font File is not found at {FONT_PATH}. Please ensure the Font is installed...")

# Progress bar function
def print_progress_bar(iteration, total, length=50):
percent = f"{100 * (iteration / float(total)):.1f}"
filled_length = int(length * iteration // total)
bar = "█" * filled_length + "-" * (length - filled_length)
sys.stdout.write(f"\r|{bar}| {percent}% Complete")
sys.stdout.flush()
if iteration == total:
print()

# Prompt user to select a word list file
def select_word_file():
print(f"Please select a TXT File or a CSV File containing the Word List to use for the Word Search(es)...")
root = Tk()
root.withdraw()  # Hide the root window
file_path = filedialog.askopenfilename(
filetypes=[("Text Files", "*.txt"), ("CSV Files", "*.csv")]
)
if not file_path:
raise FileNotFoundError("No TXT File or CSV File selected. Exiting now...")
return file_path

# Load words from the selected file
def load_word_list(file_path):
print(f"Loading the selected TXT File or a CSV File containing the Word List to use for the Word Search(es)...")
display_words = []
search_words = []
try:
with open(file_path, mode="r", encoding="utf-8") as file:
for line in file:
if "," in line:
parts = line.strip().split(",", 1)
display_words.append(parts[0].strip().upper())
search_words.append(parts[1].strip().upper())
except Exception as e:
raise RuntimeError(f"Runtime Error - Error reading TXT File or CSV File: {e}...")
if not display_words or not search_words:
raise ValueError("No valid Words found in the TXT File or CSV File.  Please ensure the format is comma separated such as 'Mozilla FireFox,MozillaFireFox'...")
return display_words, search_words

# Create an empty grid
def create_blank_grid(size):
return [[" " for _ in range(size)] for _ in range(size)]

# Place words randomly in the grid
def place_words_in_grid(grid, words):
directions = [(0, 1), (1, 0), (1, 1), (-1, 1)]  # Right, Down, Diagonal Down, Diagonal Up
size = len(grid)
for word in words:
placed = False
attempts = 0
while not placed and attempts < 500:  # Increased attempts
row, col = random.randint(0, size - 1), random.randint(0, size - 1)
dr, dc = random.choice(directions)
if can_place_word(grid, word, row, col, dr, dc):
for i, letter in enumerate(word):
grid[row + i * dr][col + i * dc] = letter
placed = True
attempts += 1
if not placed:
print(f"Warning: Failed to place the Word '{word}' into the grid.  Word will be skipped...")

# Check if a word can be placed
def can_place_word(grid, word, row, col, dr, dc):
size = len(grid)
for i, letter in enumerate(word):
r, c = row + i * dr, col + i * dc
if not (0 

Подробнее здесь: [url]https://stackoverflow.com/questions/79196316/python-word-search-generator-formatting-and-page-positioning[/url]
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»