我一直在尝试使用 python 创建一个程序,该程序将获取用户提交的文本,并将其字母打乱成一个矩阵(计算字母字符数,排除符号和空格并生成有问题的矩阵,将其填充字母按随机顺序排列)。该程序的第二部分查看该矩阵并尝试以与“单词搜索”拼图中相同的方式查找单词。该程序搜索存储在外部 .json 文件中的特定单词。这两部分似乎工作正常。我需要程序做的最后一件事——也是给我带来麻烦的事情——是打印出突出显示程序找到的单词的矩阵(或者以不同的颜色,或者粗体,或者将它们设置为大写,等等)。我不太精通Python,所以我所做的其他一切都是通过将论坛的建议以及在某些情况下人工智能的建议拼凑在一起,所以我不知道程序的问题出在哪里。一直使用 Visual Studio Code 作为环境,以防万一。
这是有问题的代码:
from colorama import init, Fore, Back, Style
init() # Initialize Colorama
import random
import math
import json
def generate_matrix(text):
# Remove spaces, commas, periods, numbers, and other symbols from the text
allowed_characters = ''.join(c for c in text if c.isalpha())
# Convert to lowercase
allowed_characters = allowed_characters.lower()
# Get the length of the text and calculate the size of the square matrix
length = len(allowed_characters)
matrix_size = int(round(math.sqrt(length)))
# Fill the text with white spaces to complete the square matrix
allowed_characters = allowed_characters + ' ' * (matrix_size ** 2 - length)
# Create a list with the allowed characters
characters = list(allowed_characters)
# Randomly shuffle the characters
random.shuffle(characters)
# Create the square matrix
matrix = [characters[i:i+matrix_size] for i in range(0, matrix_size**2, matrix_size)]
return matrix
def search_words(matrix, words):
found = []
for word in words:
for i, row in enumerate(matrix):
if word in row:
# Highlight the letters of the found word in red
highlighted_word = ''.join(
[Fore.RED + letter + Style.RESET_ALL if letter in word else letter for letter in row])
found.append(highlighted_word)
break
else:
for j in range(len(matrix[0])):
if word in ''.join(row[j] for row in matrix):
# Highlight the letters of the found word in red
highlighted_word = ''.join(
[Fore.RED + matrix[i][j] + Style.RESET_ALL if matrix[i][j] in word else matrix[i][j] for i in
range(len(matrix))])
found.append(highlighted_word)
break
else:
diagonal = ''.join(matrix[i][i] for i in range(len(matrix)))
if word in diagonal:
# Highlight the letters of the found word in red
highlighted_word = ''.join(
[Fore.RED + matrix[i][i] + Style.RESET_ALL if matrix[i][i] in word else matrix[i][i] for i in
range(len(matrix))])
found.append(highlighted_word)
else:
diagonal_inverted = ''.join(matrix[i][len(matrix) - 1 - i] for i in range(len(matrix)))
if word in diagonal_inverted:
# Highlight the letters of the found word in red
highlighted_word = ''.join(
[Fore.RED + matrix[i][len(matrix) - 1 - i] + Style.RESET_ALL if
matrix[i][len(matrix) - 1 - i] in word else matrix[i][len(matrix) - 1 - i] for i in
range(len(matrix))])
found.append(highlighted_word)
return found
# Read words from the JSON file
with open('words_dictionary.json', 'r') as file:
words_to_search = json.load(file)
# Filter out words that are less than four characters long
words_to_search = [word for word in words_to_search if len(word) >= 4]
# Ask the user to input a text
text_input = input("Enter a text: ")
# Generate the square matrix
generated_matrix = generate_matrix(text_input)
# Print the generated matrix
print("Generated matrix:")
for row in generated_matrix:
print(' '.join(row))
# Search for words in the matrix
found_words = search_words(generated_matrix, words_to_search)
# Print the found words
if found_words:
print("\nFound words:")
for word in found_words:
print(word)
else:
print("\nNo words found.")
这是输出的图像:
这是我尝试用红色突出显示单词,但我也尝试将它们变成大写和粗体,得到了类似的结果。这个想法是打印出相同的生成矩阵,并将其中的单词显示为红色(或其他)。非常感谢大家的帮助,如果您需要我提供任何其他信息,请告诉我!
您查找和突出显示单词的逻辑变得有点复杂。在某种程度上,这是不可避免的,但你会发现,如果你把它分解成小块,你会变得更容易。我建议从那部分开始。
您知道您需要突出显示矩阵中的特定字母。创建一个函数来做到这一点,与特定单词无关。参数将是矩阵和指定应突出显示哪些字母的坐标对列表。返回值是带有必要突出显示的矩阵的副本。
def highlight_chars(matrix, indices):
result = matrix.copy()
for i, j in indices:
result[i][j] = Fore.RED + matrix[i][j] + Style.RESET_ALL
return result
一旦掌握了这些,您就可以开始编写函数来查找单词并输出这些单词中字母的坐标。我会为每个搜索方向编写一个单独的函数。这里有一些可以帮助您入门:
def find_horizontal(matrix, words):
indices = []
for i, row in enumerate(matrix):
row_str = ''.join(row)
for word in words:
start_index = row_str.find(word)
if start_index >= 0:
for k in range(len(word)):
indices.append((i, start_index + k))
return indices
def find_vertical(matrix, words):
indices = []
for j in range(len(matrix[0])):
column_str = ''.join(row[j] for row in matrix)
for word in words:
start_index = column_str.find(word)
if start_index >= 0:
for k in range(len(word)):
indices.append((start_index + k, j))
return indices
如果您想添加对角线和向后搜索等功能,您应该能够使用类似的方法轻松实现这些功能。
最后,将其与您的
search_words()
函数结合在一起:
def search_words(matrix, words):
indices = find_horizontal(matrix, words)
indices += find_vertical(matrix, words)
found = highlight_chars(matrix, indices)
return found
请注意,这将返回一个矩阵,因此您需要以与打印第一个矩阵相同的方式逐行打印它。
不幸的是,如果您使用大型单词词典(例如this one,包含超过 370,000 个单词),您最终可能会突出显示更多内容,从而使输出难以解析。